How can I get Perl to give a warning message when importing a specific package / tag?

I have a package that I just created, and I have an “old mode” that basically makes it work the way it worked before: import everything into the current namespace. One of the nice things about being a package is that we no longer need to do this. Anyway, I would like to make it so that whenever someone:

use Foo qw(:oldmode); 

I warn you that this is deprecated and that they should either import only what they need, or simply access the functions using Foo-> fun ();

Any ideas on how to do this?

+6
import perl warnings packages
source share
2 answers

Well, since you specifically state that you want to signal in cases use Mod qw<:oldmode>; This works better:

 package Foo; use base qw<Exporter>; use Carp qw<carp>; ... sub import { #if ( grep { $_ eq ':oldmode' } @_ ) { # Perl 5.8 if ( @_ ~~ ':oldmode' ) { # Perl 5.10 carp( 'import called with :oldmode!' ); } goto &{Exporter->can( 'import' )}; } 

Thanks to Frew for mentioning Smart Match Perl 5.10 syntax. I learn all the ways Perl 5.10 works in my code.

Note. the standard way to use the exporter in the import unit is to either manipulate $Exporter::ExportLevel or call Foo->export_to_level( 1, @_ ); But I like the above. It is faster and, I think, easier.

+11
source share

You write your own sub import in package Foo , which is called using the parameter list from use Foo .

Example:

 package Foo; use Exporter; sub import { warn "called with paramters '@_'"; # do the real import work goto &{Exporter->can('import')}; } 

So, in sub import you can search the argument list for the deprecated tag and then throw a warning.

Update: As Axeman points out, you should call goto &{Exporter->can('import')} . This goto form replaces the current subroutine call with the stack, storing the current arguments (if any). This is necessary because the Export () import method exports to the namespace of the calling object.

+12
source share

All Articles