This is sort of like the differences between my
, our
, and local
. The differences are important, but you should be using my
99% of the time.
Perl is a fairly old and crufty language. It has evolved over the years from a combination awk/shell/kitchen sink language into a stronger typed and more powerful language.
Back in Perl 3.x days before the concept of modules and packages solidified, there was no concept of modules having their own namespace for functions and variables. Everything was available everywhere. There was nothing to import. The use
keyword didn't exist. You always used require
.
By the time Perl 5 came out, modules had their own storage for variable and subroutine names. Thus, I could use $total
in my program, and my Foo::Bar
module could also use $total
because my $total
was really $main::total
and their $total
was really $Foo::Bar::total
.
Exporting was a way to make variables and subroutines from a module available to your main program. That way, you can say copy( $file, $tofile);
instead of File::Copy::copy( $file, $tofile );
.
The use
keyword simply automated stuff for you. Plus, use
ran at compile time before your program was executed. This allows modules to use prototyping, so you can say foo( @array )
instead of foo( \@array )
or munge $file;
instead of munge( $file );
As it says in the use perldoc's page:
It [use] is exactly equivalent to:
BEGIN { require Module; Module->import( LIST ); }
Basically, you should be using use
over require
99% of the time.
I can only think of one occasion where you need to use require
over use
, but that's only to emulate use
. There are times when a module is optional. If Foo::Bar
is available, I may use it, but if it's not, I won't. It would be nice if I could check whether Foo::Bar
is available.
Let's try this:
eval { use Foo::Bar; };
my $foo_bar_is_available = 1 unless ($@);
If Foo::Bar
isn't available, I get this:
Can't locate Foo/Bar.pm in @INC (@INC contains:....)
That's because use
happens BEFORE I can run eval on it. However, I know how to emulate use
with require
:
BEGIN {
eval { require Foo::Bar; Foo::Bar->import( qw(foo bar barfu) ); };
our foo_bar_module_available = 1 unless ($@);
}
This does work. I can now check for this in my code:
our $foo_bar_module_available;
if ( $foo_bar_module_available ) {
fubar( $var, $var2 ); #I can use it
}
else {
... #Do something else
}
foo('stuff')
andbar($var)
. If there also is a subasdf
inModule
, you can still call that by sayingModule::asdf($whatever)
. – Tiradoperldoc -f use
,perldoc -f require
– Earthbounduse Module qw(foo bar) # it will load foo and bar only
is wrong. It will load (execute) the whole.pm
just as if you had doneuse Module;
. Assuming the module has a standardimport
, the difference is that the first does*caller::sub = \⊂
forfoo
andbar
, and the later does it for everything in@EXPORT
. – Newcastle