Perl use vs. require 

Joined:
04/09/2007
Posts:
776

February 09, 2011 13:27:51    Last update: February 09, 2011 13:27:51
By the perldoc,
use Module LIST;

is exactly equivalent to:
BEGIN { require Module; Module->import( LIST); }

Because of the BEGIN block, use is executed immediately. Therefore, it is not suitable for lazy loading of modules at runtime.

use does not work with a runtime variable:
C:\>perl
$cgi = "CGI";
require $cgi;
print $CGI::VERSION;
^Z
Can't locate CGI in @INC (@INC contains: C:/Perl5.8/site/lib C:/Perl5.8/lib .) at - line 2.


require works:
C:\>perl
$cgi = 'CGI';
require "${cgi}.pm";
print $CGI::VERSION;
^Z
3.48


Also, file extension is required if require is not passed a bareword:
// this works
require CGI;

// so does this
require "CGI.pm";

// but NOT this
require "CGI";

Share |
| Comment  | Tags