Normally when I am writing the perl program . I used to include following package .
use strict ;
use warnings ;
use Data::Dumper ;
Now , I want like this, I will not include all this package for every program . for that
I will have these all package in my own package. like following.my_packages.pm
package my_packages ;
{
use strict ;
use warnings ;
use Data::Dumper;
}
1;
So, that if I add my_packages.pm in perl program , it needs have all开发者_如何学运维 above packages .
Actually I have done this experimentation . But I am not able get this things . which means when I am using my_packages . I am not able get the functionality of "use strict, use warnings , use Data::Dumper ".
Someone help me out of this problem.....
Have a look at ToolSet
, which does all the dirty import work for you.
Usage example from pod:
Creating a ToolSet:
# My/Tools.pm
package My::Tools;
use base 'ToolSet';
ToolSet->use_pragma( 'strict' );
ToolSet->use_pragma( 'warnings' );
ToolSet->use_pragma( qw/feature say switch/ ); # perl 5.10
# define exports from other modules
ToolSet->export(
'Carp' => undef, # get the defaults
'Scalar::Util' => 'refaddr', # or a specific list
);
# define exports from this module
our @EXPORT = qw( shout );
sub shout { print uc shift };
1; # modules must return true
Using a ToolSet:
use My::Tools;
# strict is on
# warnings are on
# Carp and refaddr are imported
carp "We can carp!";
print refaddr [];
shout "We can shout, too!";
/I3az/
This is harder than you expect.
For pragmas like
strict
andwarnings
you can pass them through.For modules that don't export functions such as object oriented ones, it will work.
However for modules that export by default, like Data::Dumper (it gives you the
Dumper()
function in the package of the caller), it is trickier.
You can make it work by telling Exporter
that there is an extra layer of magic:
So you could do:
package my_packages;
use strict;
use warnings;
use Data::Dumper;
use IO::Socket;
$Exporter::ExportLevel = 1; # Tell Exporter to export to the caller
sub import {
# Enable this in the callers package
strict->import; # pragma in caller
warnings->import; # pragma in caller
Data::Dumper->import; # Adds Dumper() to caller
# No need for IO::Socket since it's OO.
return 1;
}
1;
For three modules, this hardly seems to be worth it.
See this:
package Foo;
use warnings;
sub import {
warnings->import;
}
1;
And now:
$ perl <<CUT
> use Foo;
> \$a = 5; # backslash just to keep the $ from being eaten by shell
> CUT
Name "main::a" used only once: possible typo at - line 2.
Taken from Modern::Perl.
精彩评论