perlfunc
gods
<P>
require - load in external functions from a library at runtime
<P>
<HR>
<P>
require
<FONT SIZE=-1>EXPR</FONT>
<P>
require
<P>
<HR>
<P>
Demands some semantics specified by
<FONT SIZE=-1>EXPR,</FONT> or by <CODE>$_</CODE> if
<FONT SIZE=-1>EXPR</FONT> is not supplied. If
<FONT SIZE=-1>EXPR</FONT> is numeric, demands that the current version of Perl (
<CODE>$]</CODE> or
<FONT SIZE=-1>$PERL_VERSION)</FONT> be equal or greater than
<FONT SIZE=-1>EXPR.</FONT>
<P>
Otherwise, demands that a library file be included if it hasn't already
been included. The file is included via the do-FILE mechanism, which is
essentially just a variety of [perlfunc:eval|eval()]. Has semantics similar to the following subroutine:
<P>
<PRE> sub require {
my($filename) = @_;
return 1 if $INC{$filename};
my($realfilename,$result);
ITER: {
foreach $prefix (@INC) {
$realfilename = "$prefix/$filename";
if (-f $realfilename) {
$result = do $realfilename;
last ITER;
}
}
die "Can't find $filename in \@INC";
}
die $@ if $@;
die "$filename did not return true value" unless $result;
$INC{$filename} = $realfilename;
return $result;
}
</PRE>
<P>
Note that the file will not be included twice under the same specified name. The file must return
<FONT SIZE=-1>TRUE</FONT> as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with ``
<CODE>1;</CODE>'' unless you're sure it'll return
<FONT SIZE=-1>TRUE</FONT> otherwise. But it's better just to put the ``<CODE>1;</CODE>'', in case you add more statements.
<P>
If
<FONT SIZE=-1>EXPR</FONT> is a bareword, the require assumes a ``<EM>.pm</EM>'' extension and replaces ``<EM>::</EM>'' with ``<EM>/</EM>'' in the filename for you, to make it easy to load standard modules. This
form of loading of modules does not risk altering your namespace.
<P>
In other words, if you try this:
<P>
<PRE> require Foo::Bar; # a splendid bareword
</PRE>
<P>
The require function will actually look for the ``<EM>Foo/Bar.pm</EM>'' file in the directories specified in the <CODE>@INC</CODE> array.
<P>
But if you try this:
<P>
<PRE> $class = 'Foo::Bar';
require $class; # $class is not a bareword
#or
require "Foo::Bar"; # not a bareword because of the ""
</PRE>
<P>
The require function will look for the ``<EM>Foo::Bar</EM>'' file in the <CODE>@INC</CODE> array and will complain about not finding
``<EM>Foo::Bar</EM>'' there. In this case you can do:
<P>
<PRE> eval "require $class";
</PRE>
<P>
For a yet-more-powerful import facility, see [perlfunc:use|use] and [perlman:perlmod|the perlmod manpage].
<HR>