Sunday, March 4, 2012

Perl study

require()

require() reads a file containing Perl code and compiles it. Before attempting to load the file, it looks up the argument in %INC to see whether it has already been loaded. If it has, then require() just returns without doing a thing. Otherwise, an attempt will be made to load and compile the file.
require() has to find the file it has to load. If the argument is a full path to the file, then it just tries to read it. For example:
  require "/home/httpd/perl/mylibs.pl";
If the path is relative, then require() will attempt to search for the file in all the directories listed in @INC. For example:
  require "mylibs.pl";
If there is more than one occurrence of the file with the same name in the directories listed in @INC, then the first occurrence will be used.
The file must return TRUE as the last statement to indicate successful execution of any initialization code. Since you never know what changes the file will go through in the future, you cannot be sure that the last statement will always return TRUE. That's why the suggestion is to put ``1;'' at the end of file.
Although you should use the real filename for most files, if the file is a module, then you may use the following convention instead:
  require My::Module;
This is equal to:
  require "My/Module.pm";
If require() fails to load the file, either because it couldn't find the file in question or the code failed to compile, or it didn't return TRUE, then the program would die(). To prevent this, the require() statement can be enclosed into an eval() exception-handling block, as in this example:
  require.pl
  ----------
  #!/usr/bin/perl -w
  
  eval { require "/file/that/does/not/exists"};
  if ($@) {
    print "Failed to load, because : $@"
  }
  print "\nHello\n";
When we execute the program:
  % ./require.pl
  
  Failed to load, because : Can't locate /file/that/does/not/exists in
  @INC (@INC contains: /usr/lib/perl5/5.00503/i386-linux
  /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux
  /usr/lib/perl5/site_perl/5.005 .) at require.pl line 3.
  
  Hello
We see that the program didn't die(), because Hello was printed. This trick is useful when you want to check whether a user has some module installed. If she hasn't, then it's not critical, because the program can run with reduced functionality without this module.
If we remove the eval() part and try again:
  require.pl
  ----------
  #!/usr/bin/perl -w
  
  require "/file/that/does/not/exists";
  print "\nHello\n";
  % ./require1.pl
  
  Can't locate /file/that/does/not/exists in @INC (@INC contains:
  /usr/lib/perl5/5.00503/i386-linux /usr/lib/perl5/5.00503
  /usr/lib/perl5/site_perl/5.005/i386-linux
  /usr/lib/perl5/site_perl/5.005 .) at require1.pl line 3.
The program just die()s in the last example, which is what you want in most cases.
For more information, refer to the perlfunc manpage.

No comments: