A module is a package of useful subroutines and variables that someone has put together. Modules extend the ability of Perl.
The File::Basename module is a standard module that is distributed with Perl. When you load the File::Basename module, you get two new functions, basename and dirname.
basename takes a long UNIX path name and returns the file name at the end. dirname takes a long UNIX path name and returns the directory part.
#!/usr/bin/perl # file: basename.pl use strict; use File::Basename; my $path = '/bush_home/bush1/lstein/C1829.fa'; my $base = basename($path); my $dir = dirname($path); print "The base is $base and the directory is $dir.\n"; |
The output of this program is:
The base is C1829.fa and the directory is /bush_home/bush1/lstein.
The use function loads up the module named File::Basename and imports the two functions. If you didn't use use, then the program would print an error:
Undefined subroutine &main::basename called at basename.pl line 8.
The Env module is a standard module that provides access to the environment variables. When you load it, it imports a set of scalar variables corresponding to your environment.
#!/usr/bin/perl # file env.pl use strict; use Env; print "My home is $HOME\n"; print "My path is $PATH\n"; print "My username is $USER\n"; |
When this runs, the output is:
My home is /bush_home/bush1/lstein My path is /net/bin:/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin:/bush_home/bush1/lstein/bin:. My username is lstein
Each module will automatically import a different set of variables and subroutines when you use it. You can control what gets imported by providing use with a list of what to import.
By default the Env module will import all the environment variables. You can make it import only some:
#!/usr/bin/perl # file env2.pl use strict; use Env '$HOME','$PATH'; print "My home is $HOME\n"; print "My path is $PATH\n"; print "My username is $USER\n"; |
Global symbol "$USER" requires explicit package name at env2.pl line 9. Execution of env2.pl aborted due to compilation errors.
You can import scalars, hashes, arrays and functions by giving a list of strings containing the variable or function names. This line imports a scalar named $PATH, an array named @PATH, and a function named printenv.
#!/usr/bin/perl use Env '$PATH','@PATH','printenv'; print join "\n",@PATH; |
Output:
/net/bin /usr/bin /bin /usr/local/bin /usr/X11R6/bin /bush_home/bush1/lstein/bin .
You will often see the qw() operator used to reduce typing:
use TestModule qw($PATH $HOME @PATH printenv); |
|
| Contents |
Next |