Section 15.1. What use Is Doing


15.1. What use Is Doing

So, just what does use do? How does the import list come into action? Perl interprets the use list as a particular form of BEGIN block wrapped around a require and a method call. For example, the following two operations are equivalent:

 use Island::Plotting::Maps qw( load_map scale_map draw_map ); BEGIN {   require Island::Plotting::Maps;   Island::Plotting::Maps->import( qw( load_map scale_map draw_map ) ); } 

Let's break this code down, piece by piece. First, the require is a package-name require, rather than the string-expression require from Chapter 10. The colons are turned into the native directory separator (such as / for Unix-like systems), and the name is suffixed with .pm (for "Perl module"). For this example on a Unix-like system, we end up with:

 require "Island/Plotting/Maps.pm"; 

Recalling the operation of require from earlier, this means Perl looks in the current value of @INC, checking through each directory for a subdirectory named Island that contains a further subdirectory named Plotting that contains the file named Maps.pm.[*] If Perl doesn't find an appropriate file after looking at all of @INC, the program dies.[] Otherwise, the first file found is read and evaluated. As always with require, the last expression evaluated must be true (or the program dies),[*] The .pm portion is defined by the interface and can't be changed. Thus, all module filenames must end in dot-p-m.

[] Trappable with an eval, of course.

These three subroutines are then defined in the File::Basename package, not the package in which our use occurs. A require'd file must return a true value, and it's traditional to use 1; as the last line of a module's code.

How do these subroutines get from the module's package into the user's package? That's the second step inside the BEGIN block. Perl automatically calls a routine called import in the module's package, passing along the entire import list. Typically, this routine aliases some of the names from the imported namespace to the importing namespace. The module author is responsible for providing an appropriate import routine. It's easier than it sounds, as discussed later in this chapter.

Finally, the whole thing is wrapped in a BEGIN block. This means that the use operation happens at compile time, rather than runtime, and indeed it does. Thus, subroutines are associated with those defined in the module, prototypes are properly defined, and so on.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net