Friday, May 18, 2007

"use" and "require" keywords

Package files in Perl can have an extension of package.pm or package.pl. Suffix .pm stands for Perl modules, and .pl are usually referred to as libraries.

We can include a package in your Perl code using either require or use. The keyword require takes a file name as an input e.g require "xyz.pl" ; The require keyword will simply include the file in your source code.

If you omit the file extension and quotes, a .pm suffix will be assumed.

The use statement is similar in that respect, but is more restrictive in that it accepts only module names, not filenames. The advantage of use is that when a program starts executing, there's a guarantee that all required modules have been successfully loaded, and there won't be any surprises at run-time unlike require.

Say for example you have a file called "sample.pm"

package sample ;
$sample_prop = 0 ;
sub sample_method {
my ($sample_amount) = @_ ;
$sample_prop +=$sample_amount (";" is missing in this line which will give compilation error)
print "Total Sample Amount $sample_prop\n";
}
return 1 ;

Here is the Perl code which uses use keyword

#/usr/bin/perl -w

use lib ("./"); #Use the current folder to find the packages ;

printf "Hello World\n";
use "sample.pm" ;
sample::sample_method(10);
sample::sample_method(20);

Here is the output
syntax error at sample.pl line 6, near "use "sample.pm""
Execution of sample.pl aborted due to compilation errors.

Here is the Perl code which uses require keyword

#/usr/bin/perl -w

use lib ("./"); #Use the current folder to find the packages ;

printf "Hello World\n";
require "sample.pm" ;
sample::sample_method(10);
sample::sample_method(20);

Here is the output

Hello World
syntax error at /sample.pm line 6, near "$sample_amount
print"
Compilation failed in require at sample.pl line 6.

As you can see the compilation error is caught when the code gets parsed when you use the use keyword, but the same error is caught during runtime when we use the require keyword (since you can see that "Hello World" gets printed during run time and then it hits the error).

Even though this might look simple now, but as you write more complex scripts getting a run time error is more dangerous compared to finding the error during parsing state.


Rahul V Shah