Perl Library Functions

by Geethalakshmi 2010-09-17 12:38:53

Perl Library Functions

require EXPR
Includes the library file specified by EXPR, or by `$_' if EXPR is not supplied. Has semantics similar to the following subroutine:

sub require {
local($filename) = @_;
return 1 if $INC{$filename};
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;

Note that the file will not be included twice under the same specified name. The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise.
Uses the value of EXPR as a filename and executes the contents of the file as a perl script. Its primary use is to include subroutines from a perl subroutine library.

do '';

is just like

eval `cat`;

except that it's more efficient, more concise, keeps track of the current filename for error messages, and searches all the `-I' libraries if the file isn't in the current directory (see section Predefined Names, for more info). It's the same, however, in that it does reparse the file every time you call it, so if you are going to use the file inside a loop you might prefer to use `-P' and `#include', at the expense of a little more startup time. (The main problem with `#include' is that cpp doesn't grok `#' comments--a workaround is to use `;#' for standalone comments.) Note that the following are NOT equivalent:

do $foo; # eval a file
do $foo(); # call a subroutine

Note that inclusion of library routines is better done with the require operator.

Tagged in:


You must LOGIN to add comments