Perl use (), require (), Do (), % INC and @ INC

Source: Internet
Author: User
Tags perl script
From: http://perl.apache.org/docs/general/perl_reference/perl_reference.html Use (), require (), Do (), % INC and @ INC explained


 


The @ INC Array


@ INCIs a special Perl variable which is the equivalent of the shell'sPathVariable. WhereasPathContains a list of directories to search for executables,@ INCContains a list of directories from which Perl modules and libraries can be loaded.



When you use (), require () or do () A filename or a module, Perl gets a list of directories from@ INCVariable and searches them for the file it was requested to load. if the file that you want to load is not located in one of the listed directories, you have to tell Perl where to find the file. you can either provide a path relative to one of the directories in@ INC, Or you can provide the full path to the file.



 


The % Inc hash


% Incis another special Perl variable that is used to cache the names of the files and the modules that were successfully loaded and compiled by use (), require () or do () statements. before attempting to load a file or a module with use () or require (), Perl checks whether it's already in the% Inchash. if it's there, the loading and therefore the compilation are not completed MED at all. otherwise the file is loaded into memory and an attempt is made to compile it. do () does unconditional loading -- no lookup in the% Inchash is made.



If the file is successfully loaded and compiled, a new key-value pair is added% Inc. The key is the name of the file or module as it was passed to the one of the three functions we have just mentioned, and if it was found in any of@ INCDirectories success t"."The value is the full path to it in the file system.



The following examples will make it easier to understand the logic.



First, let's see what are the contents@ INCOn my system:


 


% perl -e 'print join "\n", @INC'
  /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
  .


Notice.(Current Directory) is the last directory in the list.



Now let's load the moduleStrict. PMAnd see the contents% Inc:


 


 % perl -e 'use strict; print map {"$_ => $INC{$_}\n"} keys %INC'
  
  strict.pm => /usr/lib/perl5/5.00503/strict.pm


SinceStrict. PMWas found in/Usr/lib/perl5/5.00503/Directory and/Usr/lib/perl5/5.00503/Is a part@ INC,% IncProvided des the full path as the value for the keyStrict. PM.



Now let's create the simplest module in/Tmp/test. PM:


 


Test. PM ------- 1;


It does nothing, but returns a true value when loaded. Now let's load it in different ways:


 % cd /tmp
  % perl -e 'use test; print map {"$_ => $INC{$_}\n"} keys %INC'
  
  test.pm => test.pm


Since the file was found relative.(The current directory), the relative path is inserted as the value. If we alter@ INC, By adding/TmpTo the end:


 


  % cd /tmp
  % perl -e 'BEGIN{push @INC, "/tmp"} use test; \
  print map {"$_ => $INC{$_}\n"} keys %INC'
  
  test.pm => test.pm


Here we still get the relative path, since the module was found first relative".". The directory/TmpWas placed after.In the list. If we execute the same code from a different directory,"."Directory won't match,


 % cd /
  % perl -e 'BEGIN{push @INC, "/tmp"} use test; \
  print map {"$_ => $INC{$_}\n"} keys %INC'
  
  test.pm => /tmp/test.pm


So we get the full path. We can also prepend the path with unshift (), so it will be used for matching before"."And therefore we will get the full path as well:


 


 % cd /tmp
  % perl -e 'BEGIN{unshift @INC, "/tmp"} use test; \
  print map {"$_ => $INC{$_}\n"} keys %INC'
  
  test.pm => /tmp/test.pm


The code:


 


Begin {unshift @ INC, "/tmp "}


Can be replaced with the more elegant:


 


Use lib "/tmp ";


Which is almost equivalent to ourBeginBlock and is the recommended approach.



These approaches to modifying@ INCCan be labor intensive, since if you want to move the script around in the file-system you have to modify the path. this can be painful, for example, when you move your scripts from development to a production server.



There is a module calledFindbinWhich solves this problem in the plain Perl world, but unfortunately up untill Perl 5.9.1 it won't work under mod_perl, since it's a module and as any module it's loaded only once. so the first script using it will have all the settings correct, but the rest of the scripts will not if located in a different directory from the first. perl 5.9.1 provides a new functionFindbin: againWhich will do the right thing. Also the CPAN ModuleFindbin: RealProvides a working alternative working under mod_perl.



For the sake of completeness, I'll presentFindbinModule anyway.



If you use this module, you don't need to write a hard coded path. The following snippet does all the work for you (the file is/Tmp/load. pl):


 


 load.pl
  -------
  #!/usr/bin/perl
  
  use FindBin ();
  use lib "$FindBin::Bin";
  use test;
  print "test.pm => $INC{'test.pm'}\n";


In the above example$ Findbin: BinIs equal/Tmp. If we move the script somewhere else... e.g./Tmp/new_dirIn the code above$ Findbin: BinEquals/Tmp/new_dir.


 


%/Tmp/load. pl test. PM =>/tmp/test. PM


This is just likeUse libCould t that no hard coded path is required.



You can use this workaround to make it work under mod_perl.


 


 do 'FindBin.pm';
  unshift @INC, "$FindBin::Bin";
  require test;
  #maybe test::import( ... ) here if need to import stuff


This has a slight overhead because it will load from disk and recompileFindbinModule on each request. So it may not be worth it.



 


Modules, libraries and Program Files


Before we proceed, Let's define what we meanModule,LibraryAndProgram file.


  • Libraries





    These are files which contain Perl subroutines and other code.



    When these are used to break up a large program into manageable chunks they don't generally include a package Declaration; when they are used as subroutine libraries they often do have a package declaration.



    Their last statement returns true, a simple1;Statement ensures that.



    They can be named in any way desired, but generally their extension is. Pl.



    Examples:


     
    
    
    
      config.pl
      ----------
      # No package so defaults to main::
      $dir = "/home/httpd/cgi-bin";
      $cgi = "/cgi-bin";
      1;
    
      mysubs.pl
      ----------
      # No package so defaults to main::
      sub print_header{
        print "Content-type: text/plain\r\n\r\n";
      }
      1;
    
      web.pl
      ------------
      package web ;
      # Call like this: web::print_with_class('loud',"Don't shout!");
      sub print_with_class{
        my ( $class, $text ) = @_ ;
        print qq{<span class="$class">$text</span>};
      }
      1;
  • modules

    a file which contains Perl subroutines and other code.

    it generally declares a package name at the beginning of it.

    modules are generally used either as function libraries (which . pl files are still but less commonly used for), or as object libraries where a module is used to define a class and its methods.

    its last statement returns true.

    the naming convention requires it to have a . PM extension.

    example:

     MyModule.pm
      -----------
      package My::Module;
      $My::Module::VERSION = 0.01;
      
      sub new{ return bless {}, shift;}
      END { print "Quitting\n"}
      1;
  • Program Files

    Using Perl programs exist as a single file. under Linux and other UNIX-like operating systems the file often has no suffix since the operating system can determine that it is a Perl script from the first line (shebang line) or if it's Apache that executes the code, there is a variety of ways to tell how and when the file shocould be executed. under Windows a suffix is normally used, for example. PlOr. PLX.

    The program file will normallyRequire ()Any libraries andUse ()Any modules it requires for execution.

    It will contain in Perl code but won't usually have any package names.

    Its last statement may return anything or nothing.


 


Require ()


Require () reads a file containing Perl code and compiles it. Before attempting to load the file it looks up the argument in% IncTo see whether it has already been loaded. If it has, 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, it just tries to read it. For example:


 


Require "/home/httpd/perl/mylibs. pl ";


If the path is relative, 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@ INCThe first occurrence will be used.



The file must returnTrueAs 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 returnTrue. That's why the suggestion is to put"1;"At the end of file.



Although you shoshould use the real filename for most files, if the file is a module, you may use the following Convention instead:


 


Require my: module;


This is equal:


 


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 returnTrue, Then the program wocould 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 (), becauseHelloWas printed. ThisTrickIs useful when you want to check whether a user has some module installed, but if she hasn't it's not critical, perhaps the program can run without this module with protected CED functionality.



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.



 


Use ()


Use (), just like require (), loads and compiles files containing Perl code, but it works with modules only and is executed at compile time.



The only way to pass a module to load is by its module name and not its filename. If the module is located inMycode. PM, The correct way to use () It is:


 


Use mycode


And not:


 


Use "mycode. PM"


Use () translates the passed argument into a file name replacing::With the operating system's path separator (normally/) And appending. PMAt the end. SoMy: ModuleBecomesMy/module. PM.



Use () is exactly equivalent:


 


Begin {require module; Module-> Import (list );}


Internally it callrequire () to do the loading and compilation chores. When require () finishes its job, import () is called unless()Is the second argument. The following pairs are equivalent:


 


 use MyModule;
  BEGIN {require MyModule; MyModule->import; }
  
  use MyModule qw(foo bar);
  BEGIN {require MyModule; MyModule->import("foo","bar"); }
  
  use MyModule ();
  BEGIN {require MyModule; }


The first pair exports the default tags. This happens if the module Sets@ ExportTo a list of tags to be exported by default. The module's manpage normally describes what tags are exported by default.



The second pair exports only the tags passed as arguments.



The third pair describes the case where the caller does not want any symbols to be imported.



Import ()Is not a builtin function, it's just an ordinary static method call into"Mymodule"Package to tell the module to import the list of features back into the current package. See the exporter manpage for more information.



When you write your own modules, always remember that it's better to use@ Export_ OKInstead@ Export, Since the former doesn't export symbols unless it was asked to. Exports pollute the namespace of the module user. Also avoid short or common symbol names to reduce the risk of name clashes.



When functions and variables aren't exported you can still access them using their full names, like$ My: module: barOr$ My: module: Foo (). By convention you can use a leading underscore on names to informally indicate that they areInternalAnd not for public use.



There's a corresponding"No"Command that un-imports symbols importedUse, I. e., It CILSModule-> unimport (list)InsteadImport ().



 


Do ()


While do () behaves almost identically to require (), It reloads the file unconditionally. It doesn't check% IncTo see whether the file was already loaded.



If do () cannot read the file, it returnsUNDEFAnd Sets$!To report the error. If do () can read the file but cannot compile it, it returnsUNDEFAnd puts an error message in$ @. If the file is successfully compiled, do () returns the value of the last expression evaluated.



 



Complete!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.