Softpanorama

May the source be with you, but remember the KISS principle ;-)
Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Perl modules

 News

Books

Recommended Links Recommended Articles CPAN Perl namespaces  

 

Getopt::Std Getopt::Long Net::ftp Net::netrc Benchmark Net::Telnet File::Find  
 Expect.pm Reimplementation of Unix tools Pipes in Perl Debugging Tips Beautifiers Humor Etc

Perl module is a package within a file which uses its own namespace. It's a collection of subroutines and variables.

 Some subroutines can be "exposed" - visible in the namespace into which you incorporate the module. In Perl you need to export your functions and variables to the outside namespace explicitly

Technically, Perl module is just a set of conventions for using Perl's package mechanism. But this set of convention was universally adopted and became standard defacto.  For example exporting subroutines names into the namespace of the invoking script via @EXPORT mechanism provided by exporter

A Module is a collection of related subroutines and data designed to be used by other programs or modules. Modules are defined in separate files and use the package keyword to define a namespace for the data and subroutines in that module file.

A Module can be a simple collection of subroutines, not defining a class. Such modules are referred to as libraries.

A Class is a user-defined data type. Classes are defined in modules using special constructs that allow you to create variables of that type. The subroutines in these modules are referred to as methods.

An Object is a variable that belongs to a particular class. It contains its own, private data that can be operated on by the methods defined in the class. The object is called an instance of its class.

Example:

What's up with all the double colons (::)? The :: corresponds to a filesystem path separator. A Module called Shape::Rect corresponds to a file named Shape/Rect.pm relative to a module library directory. 

Perl comes with a large library of modules. In recent version it is essentially too big to be useful.  But you can be selective.

As modules use their own namespace they cannot conflict with variable in your code and thus they enhance code reuse.

A huge archive of Perl modules CPAN (Comprehensive Perl Archive Network) was collected over the time.

Some useful modules for system administration are:

use is executed at compile time.

You load modules into your namespace using use statement. It is executed at compile time, not run time.  You can't use modules conditionally.

Exporters

Since modules are usually packages stored in a file, a subroutine in the Text::Wrap module, for example, would normally be encapsulated in the namespace of Text::Wrap package. However, let's say it would be more convenient for us to export the name of the subroutines in the namescape of the package we're currently in – usually the main package. To do this, Perl uses a module called Exporter , which provides it with a way of importing subroutines from the module into the caller's package.

When you use a module, as well as reading and executing the code, Perl will try and run a subroutine called import inside the module's package. If that's not found, nothing happens, and there's no error. If it is found, though, it's called with all the parameters given on the use line. So, for instance:

use Simple("Valid", "Fake");

loads the Simple module and then runs:

Simple::import("Valid", "Fake");

Theoretically, this import subroutine could do anything. In fact, a few modules use it to let you pass parameters to setup the module. However, you'll usually want to use it to import subroutines and variables.

Exporter lets the modules that use it borrow a standard import subroutine. This subroutine checks a number of variables inside the module as well as the parameters that we give it. If we give an empty list, like this:

use Simple ();
then nothing will be imported. In this case if we wan to call a particular subroutine, for example Valid()  we need call it as Simple::Valid().

@EXPORT and @EXPORT_OK array control export of names into outside namespace

Those two array allows to export the functions and variables of modules to the namespace where use statement is issued.  @EXPORT and @EXPORT_OK are the two main variables that control export of variable from the module to outside namespace.

If the name was defined in @EXPORT_OK the name can be exported tibut you need to do it explisidly by providing this name in the list of parameters in use statement. In other words it should be mentioned in use statement explicitly.  For example it is common to list all subroutines that the module is prepared to export in this array. you do not nessesary want to export all of them by default, as some of them are for special cases only. 

So if, for instance, I want to allow use subroutines Valid() , Fake()  without package qualification I need to populate the variable

package Simple; 
use warnings; 
use strict; 
use Exporter; # this is obligatory statement (module convention)
our @ISA = qw(Exporter); # this is obligatory statement (module convention)
our @EXPORT = qw(Test); # Optional, but typically is present; you need it only if you exprot some suroutnes or variables expelisidly
our @EXPORT_OK = qw(Valid Fake); # Optional but typically is present. This is the list of variables and subroutines that you can export explisidly
#
# List of your variables and subroutines
#
sub Test { print "This is a test\n";
sub Valid { print "Valid\n" }
sub Fake { warn "Fake" }
EXPORT defines names that will be exported by default. In the example below, if we don't pass any parameters to use statement at all, only subroutine Fake that is defined in @EXPORT will be exported .
package Simple;
use warnings;
use strict;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(Valid Fake); # defaults
our @EXPORT = qw(Fake); # subroutnes
sub Valid { print "Valid" }
sub Fake { warn "Fake" }
and we ran
use Simple ; 

in our main program, we'd be able to call Fake() from the main program, but not Valid() or  – we would have to call these as Simple::Valid().

We can also define tags with the %EXPORT_TAGS hash. This allows us to group together a bunch of subroutines or variables under a group name. For instance, the CGI module allows us to say:

use CGI qw(:standard); 

which will import all its most useful subroutines.

use Exporter

The statement use Exporter lets you 'Export' functions and variables into the namespace where use statement was executed.

module Simple.pm:
package Simple;
sub Valid { print "Valid" }
sub Fake { warn "Fake" }

Now let's call subroutine Valid from the main script:

client (client.p):
use Simple;
print Simple::Valid(); 

We use print Simple::Valid(). We had to fully qualify the namespace to the function that we were using. If you exported this function instead, you could say:

use Simple;

print Valid();

without knowing that 'Valid()' was inside 'Simple'.

How to do this? Well, Perl provides Exporter to do this very thing. You say:

module Simple.pm
package Simple;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(Valid);

Don't worry about the mechanics of how this works for now. All lines 2-4 are saying is 'Export the function Sub1 into any place that says "use Simple"' This is called 'Exporting by default'. When you say:

use SimpleCrypto;

in your script, what Perl does is load up SimpleCripto, and then magic happens, copying the PigLatin function into the namespace where 'use Simple' is called. 

Anyway, 'exporting by default' is not necessarily the best thing to do. There are two nasty things that can happen:

  1. You can forget about where your functions are coming from. There is something more disciplined approach  to write SimpleCrypto::PigLatin() instead of 'PigLaticValid()', because you know exactly where to look in case of problems.
  2. Since there is a lot of stuff going on here ( inheritance, globbing, using the import function, etc) you are best off knowing about how it works, before actually using it.

The documentation has a lot more in the way of examples on 'use Exporter'. You don't need to necessarily 'export by default', you can export by choice, give a list of patterns to export (or not export) export variables, and so on. Go to the documentation for more information.

@INC and %INC

The best way to avoid problems with loading the wrong libraries or modules is to understand how Perl actually finds the libraries that it is to load into memory. We cover this in detail below.

The central variable here is called @INC (short for include) and if you remember anything out of this section, remember this.

@INC is an array provided by Perl which tells Perl (and you) the directories to search to find libraries and modules. 90% of your problems with version mis-management can be solved by this simple statement put at the beginning of your program:

print "@INC\n";

This gives you a list of places that Perl is looking to find your libraries. Here is the central rule about @INC that you should remember: Perl goes through each of the directories in order looking for the module or library that you are including. If it cannot find it in one directory, it goes to the next.

Printing out @INC shows exactly which order Perl is taking to get the libraries.

This seems to be confusing for some, so let's go further into an example on the way Perl actually does this lookup, and a session in trouble-shooting.

Suppose you have a use statement:

use Devel::Peek;

and you find out that Perl is saying something like:

Can't locate Devel::Peek in @INC at line

Well, the first thing to do is comment out the offending line (use Devel::Peek) to get a 'working' program, and print out the "@INC\n" variable as the script sees it, to get something like:

/usr/local/lib/perl5 /usr/local/lib/perl5/sun4-solaris . /home/ed/WORK/Devel

Good enough. The second thing to do is print out what is in each of those directories:

/usr/local/lib/perl5: <Bunch of files, no Devel directory>

/usr/local/lib/perl5/sun4-solaris: <Bunch of files, no Devel directory>

.: <Bunch of files, no Devel directory>

/home/ed/WORK/Devel: Peek.pm, SelfStubber.pm

Now, in tracing this down, what we do is 'follow in Perl's footsteps'. Perl goes through the following machinations:

  1. Perl looks in /usr/local/lib/perl5, and tries to find /usr/local/lib/perl5/Devel/Peek.pm.
  2. It fails, so it goes to the next directory (/usr/local/lib/perl5/sun4-solaris) and tries to find /usr/local/lib/perl5/sun4-solaris/Devel/Peek.pm.
  3. It fails here, too, so it goes to the next directory (., or the current working directory) and tries to find ./Devel/Peek.pm.
  4. This fails, so it finally goes to /home/ed/WORK/Devel to find /home/ed/WORK/Devel/Devel/Peek.pm.
  5. It finally gives up and registers an error.

Note one important thing here. Perl does not find 'Peek.pm' inside '/home/ed/WORK/Devel'. Why? Because the directory '/home/ed/WORK/Devel' is the root directory that Perl tries to match. It sticks Devel/Peek.pm on the end of the root, to get:

/home/ed/WORK/Devel/Devel/Peek.pm

So, in solving the problem, we notice that there is an extra 'Devel' on the end of our @INC which is causing mischief. The simple solution therefore is to change @INC to include /home/ed/WORK instead of /home/ed/WORK/Devel.

Array @INC and Perl's Process of Including Libraries

This is fairly straightforward if you understand "Perl-think". Learning include paths like Perl's will pay off tenfold (in other compilers, tools, etc.) It is quite a common design tactic in computer science.

Setting @INC

The variable @INC is such an important beastie to Perl that there are several different ways of setting its value. Each way has its advantages and disadvantages, you should be aware of them all (especially when debugging projects!)

The Default Value of @INC

Unlike most variables in Perl, the default value of @INC is not blank. Instead, it is a value that is set at the moment which Perl has been compiled. If you look inside the config.sh file that comes with your Perl distribution, you will see this value. (Or, probably easier, the one line script 'perl -e 'print "@INC\n"' will do the same.)

This path points to the place where the Perl installation has put all of the libraries that came with the standard distribution (see the namespace diagram up above).

The Environmental Variable PERL5LIB

The first way you should know about setting @INC is via the environmental variable PERL5LIB. This is a good way to set the environment for the purposes of a cron job, or to set the environment temporarily so you can test out new code.

If you say something like:

prompt> set PERL5LIB = "my_path";

on Win32, or:

prompt> export PERL5LIB="my_path";

on ksh, then you prepend 'my_path' to the @INC variable. Hence, if @INC was:

"/usr/local/lib/perl5", "/usr/local/lib/perl5/sun-solaris"

it becomes:

"my_path", "/usr/local/lib/perl5", "/usr/local/lib/perl5/sun-solaris"

with 'my_path' being the first place that Perl will search for libraries.

Setting PERL5LIB does have some drawbacks however. Since you are setting the environment rather than putting your instructions into the code itself, you have to be very careful when moving between environments. Forgetting to set PERL5LIB is an easy thing to do, hence caution is advised.

use lib 'my_path'

'use lib "my_path"' is the second way to set @INC, and is probably the best, most stable way of doing it. It has the following benefits:

  1. It is done inside code, hence you see exactly what is going on.
  2. ) it works well with some Perl internals (in particular, MakeMaker, which you can read about in the Perl on-line documentation.)
  3. 3) it uses a module, so your code will get benefits automatically of any further enhancements to the @INC mechanism.

When you say:

use lib 'my_path';

at the beginning of any code, Perl does exactly the same thing as with PERL5LIB. Namely, it takes 'my_path' and prepends it to "@INC".

Setting @INC directly

Finally, we mention the fact that you can set @INC directly, for closure. But to tell the truth, it is not such a good idea. You can say

BEGIN { unshift(@INC, "my_path"); }

which does the same thing as both PERL5LIB and:

use lib "my_path"

but it is unclear, ugly, and non-encapsulated. (i.e.: it shows the guts of the logic rather than hiding the details).

So do yourself a favor and stick to the two other methods!

 

%INC.

@INC is fairly well known by people who program Perl regularly, but %INC is not. This is unfortunate, because %INC can be used to track down problems that would take a lot longer time to track down with @INC. If @INC contains a list of directories that Perl searches for modules, then %INC contains a list of actual modules that Perl has loaded from the environment. For example, the following code:

use Benchmark;

foreach $key (sort keys(%INC)) {

print "$key => $INC{$key}\n";

}

will print out:

Benchmark => '/usr/local/lib/perl5/Benchmark.pm'

assuming that '/usr/local/lib/perl5' is the first library that Perl stumbles across.

As you can see, this can be extremely helpful. For one thing, it can save you the trouble of searching through the include path (@INC) to find a library out of sync, but more importantly it is exactly what Perl sees, so there is no chance of human error in tracing down these problems.

It also has one more benefit, one which you will get without any effort on your part, but you will be grateful for (trust me!). Take the following code:

for ($xx = 0; $xx < 10; $xx++) {

require "lib1.pl";

}

On the face of it, this code would cause the library lib1.pl to be included several times. In most languages, this would cause severe problems. C++, for instance, has 'compile guards' which are put around all header files. Something like this:

#ifndef HEADERA

#define HEADERA 1

#include "headera.h"

#endif

This is essentially a hack to prevent a header from being included several times (and getting 'xxx redefined' errors!).

Perl does not need this. Instead, each time a Perl library is included into your script, Perl records the fact inside %INC. The next time that library is encountered in require or use, Perl recognizes that fact, and stops right there! Hence, no problems, and a vast saving of time and resources.

Anyway, let's use %INC to solve another resource problem. Suppose that you have written a script, and get several weird errors, such as:

Undefined subroutine File::Path::seek() line ...

Now, File::Path is a module that you have written to do basic things like open a bunch of files (say in a 'tree' format), and when you open up the file 'File/Path.pm', and whatever else, you do see the subroutine named seek. Furthermore, the module 'File/Path.pm' is in your @INC variable when you start Perl.

After a couple of minutes of double-checking yourself, your first reaction should be that this is a path problem. That somehow, you are including the wrong module into your program (Perl doesn't lie, after all!).

Therefore, you should insert the following line into your program:

foreach $key (sort keys(%INC)) { print "$key => $INC{$key}\n"; }

This is exactly like we did before, except now that we run the program, we see (in the midst of the output):

File::Path => /usr/local/lib/perl5/File/Path.pm

So, at a glance, you see that somehow, '/usr/local/lib/perl5' has a module 'File/Path.pm' instead of the expected '/home/ed/WORK' having 'File/Path.pm'. What has happened? You have gotten unlucky, and accidentally called your module the same name as one that is included in the central distribution! The solution? Rename your module File/MyPath.pm (and change the package definition inside) and everything compiles successfully.

In short, learning to use %INC (and @INC) can mean hours of difference in effort. Problems like the one described above can be fairly common, especially in large, large, projects, and tracking them down can be trivial, or difficult, depending on your knowledge.

Summary of the Library and Module Road Map

@INC is the one major variable which is used to actually piece together script out of the several modules and libraries that are require'd and use'd by your program.

Perl looks at @INC a directory at a time, trying to find modules. When it finds them, it notes the fact that it has found them in the hash %INC.

As @INC is so important, there are several methods for setting @INC:

1) by default, Perl looks at how you have configured Perl to find the libraries that it needs.

2) by PERL5LIB, an environmental variable. This prepends a list of directories to @INC.

3) by saying 'use lib "path"' which changes @INC at compile time.

Modules useful for system administrators

Useful modules for files and directories handling are:


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Nov 23, 2017] Simple Module Tutorial

Notable quotes:
"... Quite some years have gone by since the inital post, just want to point out that "use vars" is now considered deprecated, instead, "our" is prefered. ..."
Aug 06, 2001 | perlmonks.com
So you find the Perl docs on modules a bit confusing? OK here is the world's simplest Perl module demonstrating all the salient features of Exporter and a script that uses this module. We also give a short rundown on @INC and finish with a note on using warnings and modules. Here is the module code. MyModule.pm package MyModule; use strict; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(func1 func2); %EXPORT_TAGS = ( DEFAULT => [qw(&func1)], Both => [qw(&func1 &func2)]); sub func1 { return reverse @_ } sub func2 { return map{ uc }@_ } 1; [download]

First we get a namespace by declaring a package name. This helps ensure our module's functions and variables remain separate from any script that uses it.

Use strict is a very good idea for modules to restrict the use of global variables. See use strict warnings and diagnostics or die for more details.

We need to use the Exporter module to export our functions from the MyModule:: namespace into the main:: namespace to make them available to scripts that 'use' MyModule.

We pacify strict with the use vars declaration of some variables. We can use an 'our' declaration in 5.6+

We now set a $VERSION number and make Exporter part of MyModule using the @ISA. See perlboot for all the gory details on what @ISA is or just use it as shown.

@EXPORT contains a list of functions that we export by default, in this case nothing. Generally the less you export by default using @EXPORT the better. This avoids accidentally clashing with functions defined in the script using the module. If a script wants a function let it ask.

@EXPORT_OK contains a list of functions that we export on demand so we export &func1 &func2 only if specifically requested to. Use this in preference to just blindly exporting functions via @EXPORT. You can also export variables like $CONFIG provided they are globals not lexicals scoped with my (read declare them with our or use vars).

%EXPORT_TAGS. For convenience we define two sets of export tags. The ':DEFAULT' tag exports only &func1; the ':Both' tag exports both &func1 &func2. This hash stores labels pointing to array references. In this case the arrays are anonymous.

We need the 1; at the end because when a module loads Perl checks to see that the module returns a true value to ensure it loaded OK. You could put any true value at the end (see Code::Police ) but 1 is the convention.

MyScript.pl (A simple script to use MyModule) #!/usr/bin/perl -w use strict; # you may need to set @INC here (see below) my @list = qw (J u s t ~ A n o t h e r ~ P e r l ~ H a c k e r !); # case 1 # use MyModule; # print func1(@list),"\n"; # print func2(@list),"\n"; # case 2 # use MyModule qw(&func1); # print func1(@list),"\n"; # print MyModule::func2(@list),"\n"; # case 3 # use MyModule qw(:DEFAULT); # print func1(@list),"\n"; # print func2(@list),"\n"; # case 4 # use MyModule qw(:Both); # print func1(@list),"\n"; # print func2(@list),"\n"; [download]

We use MyModule in MyScript.pl as shown. Uncomment the examples to see what happens. Just uncomment one at a time.

Case 1: Because our module exports nothing by default we get errors as &funct1 and &funct2 have not been exported thus do not exist in the main:: namespace of the script.

Case 2: This works OK. We ask our module to export the &func1 so we can use it. Although &func2 was not exported we reference it with its full package name so this works OK.

Case 3: The ':DEFAULT' tag *should* export &func1 so you might expect the error here to concern a missing &func2. In fact Perl complains about &func1. Hmm, what is going on here. The DEFAULT tag name is special and is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT.

Case 4: We specified the export of both our functions with the ':Both' thus this works.

A note on @INC

When you issue a use MyModule; directive perl searchs the @INC array for a module with the correct name. @INC usually contains:

/perl/lib 
/perl/site/lib
.

The . directory (dot dir) is the current working directory. CORE modules are installed under perl/lib whereas non-CORE modules install under perl/site/lib. You can add directories to the module search path in @INC like this:

BEGIN { push @INC, '/my/dir' } # or BEGIN { unshift @INC, '/my/dir' } # or use lib '/my/dir'; [download]

We need to use a BEGIN block to shift values into @INC at compile time as this is when perl checks for modules. If you wait until the script is comiled it is too late and perl will throw an exception saying it can't find MyModule in @INC... The difference between pushing a value and unshifting a value into @INC is that perl searches the @INC array for the module starting with the first dir in that array. Thus is you have a MyModule in /perl/lib/ and another in /perl/site/lib/ and another in ./ the one in /perl/lib will be found first and thus the one used. The use lib pragma effectively does the same as the BEGIN { unshift @INC, $dir } block - see perlman:lib:lib for full specifics.

What use Foo::Bar means

use Foo::Bar does not mean look for a module called "Foo::Bar.pm" in the @INC directories. It means search @INC for a *subdir* called "Foo" and a *module* called "Bar.pm".

Now once we have "use'd" a module its functions are available via the fully specified &PACKAGE::FUNCTION syntax. When we say &Foo::Bar::some_func we are refering to the *package name* not the (dir::)file name that we used in the use. This allows you to have many package names in one use'd file. In practice the names are usually the same.

use Warnings;

You should test your module with warnings enabled as this will pick up many subtle (and not so subtle :-) errors. You can activate warnings using the -w flag in the script you use to test the module. If you add use warnings to the module then your module will require Perl 5.6+ as this was not available before then. If you put $^W++ at the top of the module then you will globally enable warnings - this may break *other modules* a script may be using in addition to your module so is rather antisocial. An expert coder here called tye tests with warnings but does not include them directly in his/her modules.

Hope this explains how it works.

cheers

tachyon

Update

Fixed a typo and added a few comments. Thanks to John M. Dlugosz . Rewrote and restyled tute for compatibility with versions of Perl < 5.6 thanks to crazyinsomniac . Also thanks to tye for reminding me that $^W++ is globally scoped and a bit antisocial for a module.

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

John M. Dlugosz (Monsignor) on Aug 06, 2001 at 04:30 UTC

Re: Simple Module Tutorial

Very nice, getting everything into a short page like that. But, I have a few comments:

Are you sure you want to make $VERSION a float, rather than a v-string? And if so, illustrate the three-digit convention (e.g. 5.005_001 for version 5.5.1).

I'm also shocked that your pm file doesn't use strict !

I would also suggest adding a comment to the 1; line, saying that this means "loaded OK".

-- John

tachyon (Chancellor) on Aug 06, 2001 at 05:42 UTC

Re: Re: Simple Module Tutorial


by tachyon (Chancellor) on Aug 06, 2001 at 05:42 UTC

Thanks John I've updated the text a bit in line with your suggestions. Forgot the strict in the module! Oops it is back in its rightful place right at the top. I just used the simple $VERSION numbering because this is a simple tute :-) Here is an excerpt from the Exporter manpage for those interested.

Module Version Checking The Exporter module will convert an attempt to import a number from a module into a call to $module_name->require_version($value). This can be used to validate that the version of the module being used is greater than or equal to the required version. The Exporter module supplies a default require_version method which checks the value of $VERSION in the exporting module. Since the default require_version method treats the $VERSION number as a simple numeric value it will regard version 1.10 as lower than 1.9. For this reason it is strongly recommended that you use numbers with at least two decimal places, e.g., 1.09. [download]

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

John M. Dlugosz (Monsignor) on Aug 06, 2001 at 08:18 UTC

Re: Re: Re: Simple Module Tutorial
by John M. Dlugosz (Monsignor) on Aug 06, 2001 at 08:18 UTC Yea, I just posted a tutorial on VERSION.

For compatibility with mixing decimals and v-strings, the built-in UNIVERSAL::require_version uses three decimal digits per part.

If you have $MyModule::VERSION= 1.12; (a decimal number) and do a use MyModule 1.20.1 qw/bar/ , it will tell you that the module 1.120 and you asked for 1.020, so that's OK. You expected 1.20 to be greater than 1.12, not-OK.

-- John

tye (Sage) on Aug 06, 2001 at 22:09 UTC

(tye)Re: Simple Module Tutorial

$W++ will only give you run-time warnings and will affect other packages. Personally, I don't turn on warnings in modules that I write but I do make a point of testing them with warnings turned on (by putting "#!/usr/bin/perl -w" at the top of my test scripts).

- tye (but my friends call me "Tye")

tachyon (Chancellor) on Aug 06, 2001 at 22:36 UTC

Re: (tye)Re: Simple Module Tutorial


by tachyon (Chancellor) on Aug 06, 2001 at 22:36 UTC

Thanks I changed it from the lexically scoped 'use warnings;' so that this is applicable to versions < 5.6. but as it adds little value to the tutorial and has the unwanted side effects you point out I have just deleted it - saves a few lines of dubious value. I'll add a note on testing with warnings when I have a moment.

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

johnnywang (Priest) on Aug 09, 2004 at 22:58 UTC

Re: Simple Module Tutorial

Quite some years have gone by since the inital post, just want to point out that "use vars" is now considered deprecated, instead, "our" is prefered. Another already mentioned point is not to use @EXPORT too much. So my basic module is like the following (I have a emacs function to output this):

package MyModule; use strict; use Exporter qw(import); our $VERSION = 1.00; our @ISA = qw(Exporter); our @EXPORT_OK = qw(func1 func2); our %EXPORT_TAGS = ( DEFAULT => [qw(func1)], Both => [qw(func1 func2)]); sub func1 { return reverse @_ } sub func2 { return map{ uc }@_ } 1; [download] For those emacs users, here's the simple script to generate the skeleton: (defun perl-new-module () "Generate a skeleton source for a traditional perl module." (interactive) (setq var (split-string (read-from-minibuffer "Enter module name (eg. Web::Test): "nil nil nil nil nil nil) " ")) (setq name (car var)) (insert (format "package %s;\n\n" name)) (insert "use strict;\n\n") (insert "use Exporter qw(import);\n") (insert "our @ISA = qw(Exporter);\n") (insert "our @EXPORT_OK = qw();\n") (insert "our %EXPORT_TAGS = ();\n") (insert "our $VERSION = 1.00; \n\n") (insert "\n\n\n\n\n\n") (insert "1;") (insert "\n") (previous-line 6) (end-of-line) ) [download]

adrianh (Chancellor) on Aug 10, 2004 at 00:30 UTC

Re^2: Simple Module Tutorial


by adrianh (Chancellor) on Aug 10, 2004 at 00:30 UTC

Quite some years have gone by since the inital post, just want to point out that "use vars" is now considered deprecated, instead, "our" is prefered.

Some people prefer to use our rather than use vars (I'm one of them) - but the latter is not deprecated. Both do slightly different things and many people still prefer to use vars .

beretboy (Chaplain) on Aug 18, 2001 at 15:07 UTC

Re: Simple Module Tutorial

Exellent tutorial ++! I have never understood the writing of modules till now

"Sanity is the playground of the unimaginative" -Unknown

Codmate (Novice) on Sep 06, 2001 at 20:18 UTC

Re: Re: Simple Module Tutorial


by Codmate (Novice) on Sep 06, 2001 at 20:18 UTC

Fantastic stuff - I just converted a full script into a module (and added some bits) and it worked 1st time - WITH NO DEBUGGING REQUIRED (and yes - I am using strict)!!! I was very scared of modules before but now feel like I could write a hundred. Thanks very much for this - invaluable tutorial for a newbie like me :))))))

Jaap (Curate) on Jul 22, 2002 at 09:35 UTC

Re: Simple Module Tutorial

This is a nice tutorial tachyon. Are you considering writing a more advanced tutorial on modules (combined with OO)?

Especially, what a GOOD module looks like. Should we use carp, dynaloader and what not?

gawatkins (Monsignor) on Apr 10, 2003 at 11:44 UTC

Re: Simple Module Tutorial

Great Tutorial, It helped to clear up the muddy water created by my Perl Black Book .

Thanks again,

Greg W.

twotone (Beadle) on Oct 14, 2007 at 05:06 UTC

Re: Simple Module Tutorial

Great summary of module basics!

Here's a little code I came up with to add my module location to @INC (in a cgi environment) by dynamically determining the document root for the script. It works on the remote apache server and when testing locally in windows. It might be of some interest:

BEGIN { # get doc root from %ENV # implicitly declare file root path if %ENV not fount my $doc_root = $ENV{DOCUMENT_ROOT} || 'C:/Users/User/Documents/website/sites/mysite'; # change \ to / $doc_root =~ s/\\/\//g; # add module folder location $doc_root .= "/cgi-bin/cms/"; # add module location to @INC push(@INC,$doc_root); } [download]

bychan (Initiate) on Jan 28, 2008 at 08:45 UTC

Re^2: Simple Module Tutorial


by bychan (Initiate) on Jan 28, 2008 at 08:45 UTC

This tutorial is great. The only problem is, that I get the following result, if I comment out all the cases:

!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!

Shouldn't there be some error messages or warnings?

chexmix (Hermit) on Aug 12, 2008 at 13:24 UTC

Re: Simple Module Tutorial

I like this post very much, but the following is opaque to me for some reason:

" Case 3: The ':DEFAULT' tag *should* export &func1 so you might expect the error here to concern a missing &func2. In fact Perl complains about &func1. Hmm, what is going on here. The DEFAULT tag name is special and is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT."

I confess I still don't know what is going on here, and am wondering if someone can help me out.

The words "is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT" seem inaccurate to me, since when I look up at the code for MyModule.pm, I see the line

%EXPORT_TAGS = ( DEFAULT => qw(&func1) ,

and not the line

%EXPORT_TAGS = ( DEFAULT => \@EXPORT,

Is the OP saying that the line as is in the MyModule.pm code is incorrect, because the "special" nature of DEFAULT overrides it with something else?

Thanks. I feel I am blanking on something obvious here, but just can't see it this rainy morning.

tye (Sage) on Aug 14, 2008 at 15:41 UTC

Re^2: Simple Module Tutorial (DEFAULT)


by tye (Sage) on Aug 14, 2008 at 15:41 UTC

Is the OP saying that the line as is in the MyModule.pm code is incorrect, because the "special" nature of DEFAULT overrides it with something else?

Yes. Exporter.pm wants :DEFAULT to match @EXPORT so the module is incorrect in trying to define its own meaning for :DEFAULT. Based on what you've quoted, it appears that Exporter.pm forces this issue, but the more important point is that you shouldn't set $EXPORT_TAGS{DEFAULT} yourself.

- tye

sg (Pilgrim) on Feb 05, 2011 at 23:13 UTC

Re: Simple Module Tutorial

Thanks for the exposition; my inclination regarding a simple module is as follows:

MyModule.pm package MyModule; use strict; use warnings; use diagnostics; use Carp; our $VERSION = 1.08; sub see_me { my $foo = shift; print "\t\tDo you see this: $foo?\n"; } 1; __END__ last line of the module needs to be true; last line of the _file_ need not be true: 0; [download]

The above module is exercised by the following script:

exercise_my_module.pl

#!/c/opt/perl/bin/perl use strict; use warnings; use diagnostics; use Carp; use MyModule 1.05; #use MyModule 1.10; # will fail MyModule::see_me( 8 ); __END__ [download]

chanslor (Acolyte) on Feb 27, 2015 at 19:47 UTC

Re^2: Simple Module Tutorial


by chanslor (Acolyte) on Feb 27, 2015 at 19:47 UTC

Thank you for this post! It has gotten me past the first barrier of writing my own module. Thanks again! - chanslor

Anonymous Monk on Mar 09, 2010 at 12:21 UTC

Re: Simple Module Tutorial

Excellent representation of what seemed a tough nut to swallow. Thank you very much. Tanuj Bhargava

Anonymous Monk on Mar 07, 2011 at 15:12 UTC

Re: Simple Module Tutorial

Thanks to the writer for your trouble. But everyone seems to get it except me. I have tried to duplicate your results.

I have:

- MyScript.pl under /storage/username/PERL_SCRIPTS/dev

- Test.pm under /storage/username/local/perl/site/lib/Test/Test.pm (I just replaced MyModule.pm with Test.pm).

The module code is exactly the same. In MyScript.pl I have added

use lib '/storage/username/local/perl/site/lib'; <p>and typed in the first two cases.</p> <code>perl MyScript.pl [download] gives: Undefined subroutine &main::func1 called at MyScript.pl line 10

Line 10 is:

print func1(@list),"\n";

after typing "use Test;"

What am I missing here? Also, is the BEGIN command supposed to be used in the Perl script? It gives syntax errors when I try to use it.

Thanks in advance,

Gideon

toolic (Bishop) on Mar 07, 2011 at 15:25 UTC

Re^2: Simple Module Tutorial


by toolic (Bishop) on Mar 07, 2011 at 15:25 UTC

"Test" is a poor choice of a module name because there is a Core module of the same name ( Test ) which is part of the standard Perl distribution. Furthermore, since you placed your .pm file under a directory named "Test", you would need to type use Test::Test; . I strongly recommend you change the name of your module to something more unique in order to avoid this naming collision.

Anonymous Monk on Mar 07, 2011 at 16:11 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Mar 07, 2011 at 16:11 UTC

Dear toolic,

Thank you for your reply. I now have changed all instances of "Test" with "MyModule" and also changed the name of the module. MyModule.pm is now situated on

/storage/username/local/perl/site/lib

and I use

use lib '/storage/username/local/perl/site/lib'; with the second case (as per the example): # case 2 use MyModule; print func1(@list),"\n"; print MyModule::func2(@list),"\n"; [download]

but I still get the same error: Undefined subroutine &main::func1 called at MyScript line 15.

Just to make sure I copied the module exactly from the example but to no avail. Interestingly, when I comment out the print func1 part, the line after that produces correct output. I hope that someone could point out to me where I am at fault.

Best regards,

Gideon

toolic (Bishop) on Mar 07, 2011 at 16:34 UTC

Re^4: Simple Module Tutorial
by toolic (Bishop) on Mar 07, 2011 at 16:34 UTC

Anonymous Monk on Mar 07, 2011 at 16:58 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Mar 07, 2011 at 16:58 UTC

Hi toolic

For some reason I can't reply to your latest post but thanks a mil! I did copy the module exactly but not the script. Somehow I mixed up case 1 and case 2. I expected case 1 not to work but case 2 but instead of coding

use MyModule qw(&func1);

I simply used

use MyModule;

Thanks a lot for pointing it out, it seems to work now. I have learned quite a bit.

Best regards,

Gideon

Anonymous Monk on Nov 18, 2014 at 00:13 UTC

Re: Simple Module Tutorial

Thank you for this topic, it is very useful for a beginner. However i had a trouble with use of Module.

Anonymous Monk on Nov 18, 2014 at 01:06 UTC

Re^2: Simple Module Tutorial


by Anonymous Monk on Nov 18, 2014 at 01:06 UTC

You did not post any code

Anonymous Monk on Dec 16, 2014 at 23:03 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Dec 16, 2014 at 23:03 UTC Hello, I used exactly the same code than quoted at Re: Simple Module Tutorial by johnnywang on Aug 09, 2004 at 22:58 UTC I don't get trouble with the code, but it is just that once i used the module i can't modify function in it and see the effects. It looks like library are not updated. How could we do that ?
Replies are listed 'Best First'.

[Nov 23, 2017] Simple Module Tutorial

Aug 06, 2001 | perlmonks.com
So you find the Perl docs on modules a bit confusing? OK here is the world's simplest Perl module demonstrating all the salient features of Exporter and a script that uses this module. We also give a short rundown on @INC and finish with a note on using warnings and modules. Here is the module code. MyModule.pm package MyModule; use strict; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 1.00; @ISA = qw(Exporter); @EXPORT = (); @EXPORT_OK = qw(func1 func2); %EXPORT_TAGS = ( DEFAULT => [qw(&func1)], Both => [qw(&func1 &func2)]); sub func1 { return reverse @_ } sub func2 { return map{ uc }@_ } 1; [download]

First we get a namespace by declaring a package name. This helps ensure our module's functions and variables remain separate from any script that uses it.

Use strict is a very good idea for modules to restrict the use of global variables. See use strict warnings and diagnostics or die for more details.

We need to use the Exporter module to export our functions from the MyModule:: namespace into the main:: namespace to make them available to scripts that 'use' MyModule.

We pacify strict with the use vars declaration of some variables. We can use an 'our' declaration in 5.6+

We now set a $VERSION number and make Exporter part of MyModule using the @ISA. See perlboot for all the gory details on what @ISA is or just use it as shown.

@EXPORT contains a list of functions that we export by default, in this case nothing. Generally the less you export by default using @EXPORT the better. This avoids accidentally clashing with functions defined in the script using the module. If a script wants a function let it ask.

@EXPORT_OK contains a list of functions that we export on demand so we export &func1 &func2 only if specifically requested to. Use this in preference to just blindly exporting functions via @EXPORT. You can also export variables like $CONFIG provided they are globals not lexicals scoped with my (read declare them with our or use vars).

%EXPORT_TAGS. For convenience we define two sets of export tags. The ':DEFAULT' tag exports only &func1; the ':Both' tag exports both &func1 &func2. This hash stores labels pointing to array references. In this case the arrays are anonymous.

We need the 1; at the end because when a module loads Perl checks to see that the module returns a true value to ensure it loaded OK. You could put any true value at the end (see Code::Police ) but 1 is the convention.

MyScript.pl (A simple script to use MyModule) #!/usr/bin/perl -w use strict; # you may need to set @INC here (see below) my @list = qw (J u s t ~ A n o t h e r ~ P e r l ~ H a c k e r !); # case 1 # use MyModule; # print func1(@list),"\n"; # print func2(@list),"\n"; # case 2 # use MyModule qw(&func1); # print func1(@list),"\n"; # print MyModule::func2(@list),"\n"; # case 3 # use MyModule qw(:DEFAULT); # print func1(@list),"\n"; # print func2(@list),"\n"; # case 4 # use MyModule qw(:Both); # print func1(@list),"\n"; # print func2(@list),"\n"; [download]

We use MyModule in MyScript.pl as shown. Uncomment the examples to see what happens. Just uncomment one at a time.

Case 1: Because our module exports nothing by default we get errors as &funct1 and &funct2 have not been exported thus do not exist in the main:: namespace of the script.

Case 2: This works OK. We ask our module to export the &func1 so we can use it. Although &func2 was not exported we reference it with its full package name so this works OK.

Case 3: The ':DEFAULT' tag *should* export &func1 so you might expect the error here to concern a missing &func2. In fact Perl complains about &func1. Hmm, what is going on here. The DEFAULT tag name is special and is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT.

Case 4: We specified the export of both our functions with the ':Both' thus this works.

A note on @INC

When you issue a use MyModule; directive perl searchs the @INC array for a module with the correct name. @INC usually contains:

/perl/lib 
/perl/site/lib
.

The . directory (dot dir) is the current working directory. CORE modules are installed under perl/lib whereas non-CORE modules install under perl/site/lib. You can add directories to the module search path in @INC like this:

BEGIN { push @INC, '/my/dir' } # or BEGIN { unshift @INC, '/my/dir' } # or use lib '/my/dir'; [download]

We need to use a BEGIN block to shift values into @INC at compile time as this is when perl checks for modules. If you wait until the script is comiled it is too late and perl will throw an exception saying it can't find MyModule in @INC... The difference between pushing a value and unshifting a value into @INC is that perl searches the @INC array for the module starting with the first dir in that array. Thus is you have a MyModule in /perl/lib/ and another in /perl/site/lib/ and another in ./ the one in /perl/lib will be found first and thus the one used. The use lib pragma effectively does the same as the BEGIN { unshift @INC, $dir } block - see perlman:lib:lib for full specifics.

What use Foo::Bar means

use Foo::Bar does not mean look for a module called "Foo::Bar.pm" in the @INC directories. It means search @INC for a *subdir* called "Foo" and a *module* called "Bar.pm".

Now once we have "use'd" a module its functions are available via the fully specified &PACKAGE::FUNCTION syntax. When we say &Foo::Bar::some_func we are refering to the *package name* not the (dir::)file name that we used in the use. This allows you to have many package names in one use'd file. In practice the names are usually the same.

use Warnings;

You should test your module with warnings enabled as this will pick up many subtle (and not so subtle :-) errors. You can activate warnings using the -w flag in the script you use to test the module. If you add use warnings to the module then your module will require Perl 5.6+ as this was not available before then. If you put $^W++ at the top of the module then you will globally enable warnings - this may break *other modules* a script may be using in addition to your module so is rather antisocial. An expert coder here called tye tests with warnings but does not include them directly in his/her modules.

Hope this explains how it works.

cheers

tachyon

Update

Fixed a typo and added a few comments. Thanks to John M. Dlugosz . Rewrote and restyled tute for compatibility with versions of Perl < 5.6 thanks to crazyinsomniac . Also thanks to tye for reminding me that $^W++ is globally scoped and a bit antisocial for a module.

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

John M. Dlugosz (Monsignor) on Aug 06, 2001 at 04:30 UTC

Re: Simple Module Tutorial

Very nice, getting everything into a short page like that. But, I have a few comments:

Are you sure you want to make $VERSION a float, rather than a v-string? And if so, illustrate the three-digit convention (e.g. 5.005_001 for version 5.5.1).

I'm also shocked that your pm file doesn't use strict !

I would also suggest adding a comment to the 1; line, saying that this means "loaded OK".

-- John

tachyon (Chancellor) on Aug 06, 2001 at 05:42 UTC

Re: Re: Simple Module Tutorial


by tachyon (Chancellor) on Aug 06, 2001 at 05:42 UTC

Thanks John I've updated the text a bit in line with your suggestions. Forgot the strict in the module! Oops it is back in its rightful place right at the top. I just used the simple $VERSION numbering because this is a simple tute :-) Here is an excerpt from the Exporter manpage for those interested.

Module Version Checking The Exporter module will convert an attempt to import a number from a module into a call to $module_name->require_version($value). This can be used to validate that the version of the module being used is greater than or equal to the required version. The Exporter module supplies a default require_version method which checks the value of $VERSION in the exporting module. Since the default require_version method treats the $VERSION number as a simple numeric value it will regard version 1.10 as lower than 1.9. For this reason it is strongly recommended that you use numbers with at least two decimal places, e.g., 1.09. [download]

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

John M. Dlugosz (Monsignor) on Aug 06, 2001 at 08:18 UTC

Re: Re: Re: Simple Module Tutorial
by John M. Dlugosz (Monsignor) on Aug 06, 2001 at 08:18 UTC Yea, I just posted a tutorial on VERSION.

For compatibility with mixing decimals and v-strings, the built-in UNIVERSAL::require_version uses three decimal digits per part.

If you have $MyModule::VERSION= 1.12; (a decimal number) and do a use MyModule 1.20.1 qw/bar/ , it will tell you that the module 1.120 and you asked for 1.020, so that's OK. You expected 1.20 to be greater than 1.12, not-OK.

-- John

tye (Sage) on Aug 06, 2001 at 22:09 UTC

(tye)Re: Simple Module Tutorial

$W++ will only give you run-time warnings and will affect other packages. Personally, I don't turn on warnings in modules that I write but I do make a point of testing them with warnings turned on (by putting "#!/usr/bin/perl -w" at the top of my test scripts).

- tye (but my friends call me "Tye")

tachyon (Chancellor) on Aug 06, 2001 at 22:36 UTC

Re: (tye)Re: Simple Module Tutorial


by tachyon (Chancellor) on Aug 06, 2001 at 22:36 UTC

Thanks I changed it from the lexically scoped 'use warnings;' so that this is applicable to versions < 5.6. but as it adds little value to the tutorial and has the unwanted side effects you point out I have just deleted it - saves a few lines of dubious value. I'll add a note on testing with warnings when I have a moment.

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

johnnywang (Priest) on Aug 09, 2004 at 22:58 UTC

Re: Simple Module Tutorial

Quite some years have gone by since the inital post, just want to point out that "use vars" is now considered deprecated, instead, "our" is prefered. Another already mentioned point is not to use @EXPORT too much. So my basic module is like the following (I have a emacs function to output this):

package MyModule; use strict; use Exporter qw(import); our $VERSION = 1.00; our @ISA = qw(Exporter); our @EXPORT_OK = qw(func1 func2); our %EXPORT_TAGS = ( DEFAULT => [qw(func1)], Both => [qw(func1 func2)]); sub func1 { return reverse @_ } sub func2 { return map{ uc }@_ } 1; [download] For those emacs users, here's the simple script to generate the skeleton: (defun perl-new-module () "Generate a skeleton source for a traditional perl module." (interactive) (setq var (split-string (read-from-minibuffer "Enter module name (eg. Web::Test): "nil nil nil nil nil nil) " ")) (setq name (car var)) (insert (format "package %s;\n\n" name)) (insert "use strict;\n\n") (insert "use Exporter qw(import);\n") (insert "our @ISA = qw(Exporter);\n") (insert "our @EXPORT_OK = qw();\n") (insert "our %EXPORT_TAGS = ();\n") (insert "our $VERSION = 1.00; \n\n") (insert "\n\n\n\n\n\n") (insert "1;") (insert "\n") (previous-line 6) (end-of-line) ) [download]

adrianh (Chancellor) on Aug 10, 2004 at 00:30 UTC

Re^2: Simple Module Tutorial


by adrianh (Chancellor) on Aug 10, 2004 at 00:30 UTC

Quite some years have gone by since the inital post, just want to point out that "use vars" is now considered deprecated, instead, "our" is prefered.

Some people prefer to use our rather than use vars (I'm one of them) - but the latter is not deprecated. Both do slightly different things and many people still prefer to use vars .

beretboy (Chaplain) on Aug 18, 2001 at 15:07 UTC

Re: Simple Module Tutorial

Exellent tutorial ++! I have never understood the writing of modules till now

"Sanity is the playground of the unimaginative" -Unknown

Codmate (Novice) on Sep 06, 2001 at 20:18 UTC

Re: Re: Simple Module Tutorial


by Codmate (Novice) on Sep 06, 2001 at 20:18 UTC

Fantastic stuff - I just converted a full script into a module (and added some bits) and it worked 1st time - WITH NO DEBUGGING REQUIRED (and yes - I am using strict)!!! I was very scared of modules before but now feel like I could write a hundred. Thanks very much for this - invaluable tutorial for a newbie like me :))))))

Jaap (Curate) on Jul 22, 2002 at 09:35 UTC

Re: Simple Module Tutorial

This is a nice tutorial tachyon. Are you considering writing a more advanced tutorial on modules (combined with OO)?

Especially, what a GOOD module looks like. Should we use carp, dynaloader and what not?

gawatkins (Monsignor) on Apr 10, 2003 at 11:44 UTC

Re: Simple Module Tutorial

Great Tutorial, It helped to clear up the muddy water created by my Perl Black Book .

Thanks again,

Greg W.

twotone (Beadle) on Oct 14, 2007 at 05:06 UTC

Re: Simple Module Tutorial

Great summary of module basics!

Here's a little code I came up with to add my module location to @INC (in a cgi environment) by dynamically determining the document root for the script. It works on the remote apache server and when testing locally in windows. It might be of some interest:

BEGIN { # get doc root from %ENV # implicitly declare file root path if %ENV not fount my $doc_root = $ENV{DOCUMENT_ROOT} || 'C:/Users/User/Documents/website/sites/mysite'; # change \ to / $doc_root =~ s/\\/\//g; # add module folder location $doc_root .= "/cgi-bin/cms/"; # add module location to @INC push(@INC,$doc_root); } [download]

bychan (Initiate) on Jan 28, 2008 at 08:45 UTC

Re^2: Simple Module Tutorial


by bychan (Initiate) on Jan 28, 2008 at 08:45 UTC

This tutorial is great. The only problem is, that I get the following result, if I comment out all the cases:

!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!
!rekcaH~lreP~rehtonA~tsuJ
JUST~ANOTHER~PERL~HACKER!

Shouldn't there be some error messages or warnings?

chexmix (Hermit) on Aug 12, 2008 at 13:24 UTC

Re: Simple Module Tutorial

I like this post very much, but the following is opaque to me for some reason:

" Case 3: The ':DEFAULT' tag *should* export &func1 so you might expect the error here to concern a missing &func2. In fact Perl complains about &func1. Hmm, what is going on here. The DEFAULT tag name is special and is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT."

I confess I still don't know what is going on here, and am wondering if someone can help me out.

The words "is automatically set in our modules %EXPORT_TAGS hash like this DEFAULT => \@EXPORT" seem inaccurate to me, since when I look up at the code for MyModule.pm, I see the line

%EXPORT_TAGS = ( DEFAULT => qw(&func1) ,

and not the line

%EXPORT_TAGS = ( DEFAULT => \@EXPORT,

Is the OP saying that the line as is in the MyModule.pm code is incorrect, because the "special" nature of DEFAULT overrides it with something else?

Thanks. I feel I am blanking on something obvious here, but just can't see it this rainy morning.

tye (Sage) on Aug 14, 2008 at 15:41 UTC

Re^2: Simple Module Tutorial (DEFAULT)


by tye (Sage) on Aug 14, 2008 at 15:41 UTC

Is the OP saying that the line as is in the MyModule.pm code is incorrect, because the "special" nature of DEFAULT overrides it with something else?

Yes. Exporter.pm wants :DEFAULT to match @EXPORT so the module is incorrect in trying to define its own meaning for :DEFAULT. Based on what you've quoted, it appears that Exporter.pm forces this issue, but the more important point is that you shouldn't set $EXPORT_TAGS{DEFAULT} yourself.

- tye

sg (Pilgrim) on Feb 05, 2011 at 23:13 UTC

Re: Simple Module Tutorial

Thanks for the exposition; my inclination regarding a simple module is as follows:

MyModule.pm package MyModule; use strict; use warnings; use diagnostics; use Carp; our $VERSION = 1.08; sub see_me { my $foo = shift; print "\t\tDo you see this: $foo?\n"; } 1; __END__ last line of the module needs to be true; last line of the _file_ need not be true: 0; [download]

The above module is exercised by the following script:

exercise_my_module.pl

#!/c/opt/perl/bin/perl use strict; use warnings; use diagnostics; use Carp; use MyModule 1.05; #use MyModule 1.10; # will fail MyModule::see_me( 8 ); __END__ [download]

chanslor (Acolyte) on Feb 27, 2015 at 19:47 UTC

Re^2: Simple Module Tutorial


by chanslor (Acolyte) on Feb 27, 2015 at 19:47 UTC

Thank you for this post! It has gotten me past the first barrier of writing my own module. Thanks again! - chanslor

Anonymous Monk on Mar 09, 2010 at 12:21 UTC

Re: Simple Module Tutorial

Excellent representation of what seemed a tough nut to swallow. Thank you very much. Tanuj Bhargava

Anonymous Monk on Mar 07, 2011 at 15:12 UTC

Re: Simple Module Tutorial

Thanks to the writer for your trouble. But everyone seems to get it except me. I have tried to duplicate your results.

I have:

- MyScript.pl under /storage/username/PERL_SCRIPTS/dev

- Test.pm under /storage/username/local/perl/site/lib/Test/Test.pm (I just replaced MyModule.pm with Test.pm).

The module code is exactly the same. In MyScript.pl I have added

use lib '/storage/username/local/perl/site/lib'; <p>and typed in the first two cases.</p> <code>perl MyScript.pl [download] gives: Undefined subroutine &main::func1 called at MyScript.pl line 10

Line 10 is:

print func1(@list),"\n";

after typing "use Test;"

What am I missing here? Also, is the BEGIN command supposed to be used in the Perl script? It gives syntax errors when I try to use it.

Thanks in advance,

Gideon

toolic (Bishop) on Mar 07, 2011 at 15:25 UTC

Re^2: Simple Module Tutorial


by toolic (Bishop) on Mar 07, 2011 at 15:25 UTC

"Test" is a poor choice of a module name because there is a Core module of the same name ( Test ) which is part of the standard Perl distribution. Furthermore, since you placed your .pm file under a directory named "Test", you would need to type use Test::Test; . I strongly recommend you change the name of your module to something more unique in order to avoid this naming collision.

Anonymous Monk on Mar 07, 2011 at 16:11 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Mar 07, 2011 at 16:11 UTC

Dear toolic,

Thank you for your reply. I now have changed all instances of "Test" with "MyModule" and also changed the name of the module. MyModule.pm is now situated on

/storage/username/local/perl/site/lib

and I use

use lib '/storage/username/local/perl/site/lib'; with the second case (as per the example): # case 2 use MyModule; print func1(@list),"\n"; print MyModule::func2(@list),"\n"; [download]

but I still get the same error: Undefined subroutine &main::func1 called at MyScript line 15.

Just to make sure I copied the module exactly from the example but to no avail. Interestingly, when I comment out the print func1 part, the line after that produces correct output. I hope that someone could point out to me where I am at fault.

Best regards,

Gideon

toolic (Bishop) on Mar 07, 2011 at 16:34 UTC

Re^4: Simple Module Tutorial
by toolic (Bishop) on Mar 07, 2011 at 16:34 UTC

Anonymous Monk on Mar 07, 2011 at 16:58 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Mar 07, 2011 at 16:58 UTC

Hi toolic

For some reason I can't reply to your latest post but thanks a mil! I did copy the module exactly but not the script. Somehow I mixed up case 1 and case 2. I expected case 1 not to work but case 2 but instead of coding

use MyModule qw(&func1);

I simply used

use MyModule;

Thanks a lot for pointing it out, it seems to work now. I have learned quite a bit.

Best regards,

Gideon

Anonymous Monk on Nov 18, 2014 at 00:13 UTC

Re: Simple Module Tutorial

Thank you for this topic, it is very useful for a beginner. However i had a trouble with use of Module.

Anonymous Monk on Nov 18, 2014 at 01:06 UTC

Re^2: Simple Module Tutorial


by Anonymous Monk on Nov 18, 2014 at 01:06 UTC

You did not post any code

Anonymous Monk on Dec 16, 2014 at 23:03 UTC

Re^3: Simple Module Tutorial
by Anonymous Monk on Dec 16, 2014 at 23:03 UTC Hello, I used exactly the same code than quoted at Re: Simple Module Tutorial by johnnywang on Aug 09, 2004 at 22:58 UTC I don't get trouble with the code, but it is just that once i used the module i can't modify function in it and see the effects. It looks like library are not updated. How could we do that ?
Replies are listed 'Best First'.

[Nov 16, 2017] Reading/dumping a perl hash from shell

Nov 11, 2017 | stackoverflow.com

newbie ,Nov 11 at 0:27

I have a read-only perl file with a huge hash defined in it. Is there anyway for me to read this perl file and dump out the hash contents?

this is basic structure of the hash within the file.

%hash_name = {
    -files => [
         '<some_path>',
    ],
    -dirs => [
         '<some_path>',
         '<some_path>',
         '<some_path>',
         '<some_path>',
         '<some_path>',
    ],
};

Davy M ,Nov 11 at 0:30

can you not cat the file and redirect it into a one that does have write permissions? cat perl_file_name > new_perl_file_nameDavy M Nov 11 at 0:30

newbie ,Nov 11 at 0:34

yes I did consider that but will go with that approach only if there is no other way to dump the hash without creating a new file. – newbie Nov 11 at 0:34

zdim ,Nov 11 at 2:59

@newbie Thank you, and to repeat the question: Does this file have other Perl code or just this hash? Also, is the hash undeclared (just %hash_name ), as you show it, or is it "lexical," so with my such as: my %hash_name ? – zdim Nov 11 at 2:59

zdim ,Nov 11 at 3:12

@newbie What you show is invalid in Perl: the % in %hash_name indicates that the variable is a hash , but { .. } form a hash reference , which is a scalar variable (not a hash). So it should be either %hash_name = ( .. ) or it's $hashref_name = { .. }zdim Nov 11 at 3:12

Schwern ,Nov 11 at 6:59

Note this is an insecure way to store data. The data file must be evaluated as perl code. Any arbitrary code could be in the file. In addition, the data file can only be read by Perl programs. Instead, use JSON or similar data format. JSON::MaybeXS can convert between JSON and Perl. – Schwern Nov 11 at 6:59

zdim ,Nov 11 at 3:40

Ideally you'd copy the file so that you can edit it, then turn it into a module so to use it nicely.

But if for some reason this isn't feasible here are your options.

If that hash is the only thing in the file , "load" it using do and assign to a hash

use warnings;
use strict;

my $file = './read_this.pl';  # the file has *only* that one hash

my %hash = do $file;

This form of do executes the file (runs it as a script), returning the last expression that is evaluated. With only the hash in the file that last expression is the hash definition, precisely what you need.

If the hash is undeclared , so a global variable (or declared with our ), then declare as our a hash with the same name in your program and again load the file with do

our %hash_name;  # same name as in the file
do $file;        # file has "%hash" or "our %hash" (not "my %hash")

Here we "pick up" the hash that is evaluated as do runs the file by virtues of our

If the hash is "lexical" , declared as my %hash (as it should be!) ... well, this is bad. Then you need to parse the text of the file so to extract lines with the hash. This is in general very hard to do, as it amounts to parsing Perl. (A hash can be built using map , returned from a sub as a reference or a flat list ...) Once that is done you eval the variable which contains the text defining that hash.

However, if you know how the hash is built, as you imply, with no () anywhere inside

use warnings; 
use strict;

my $file = './read_this.pl';

my $content = do {  # "slurp" the file -- read it into a variable
    local $/;
    open my $fh, '<', $file or die "Can't open $file: $!";
    <$fh>;
};

my ($hash_text) = $content =~ /\%hash_name\s*=\s*(\(.*?\)/s;
my %hash = eval $hash_text;

This simple shot leaves out a lot, assuming squarely that the hash is as shown. Also note that this form of eval carries real and serious security risks.


Files are also loaded using require . Apart from it doing a lot more than do , the important thing here is that even if it runs multiple times require still loads that file only once . This matters for modules in the first place, which shouldn't be loaded multiple times, and use indeed uses require .

On the other hand, do does it every time, what makes it suitable for loading files to be used as data, which presumably should be read every time. This is the recommended method. Note that require itself uses do to actually load the file.

Thanks to Schwern for a comment.

Schwern ,Nov 11 at 4:31

do will always load the file. require will only load it once. Since you want to get data from the file, it's recommended to use do . Else the second or third time anything in that process loads the file they'll end up with 1 . – Schwern Nov 11 at 4:31

zdim ,Nov 11 at 4:41

@Schwern Right, thank you for the comment. I wanted to avoid excessive explanation thus I simply use do . (I still mention require since it is feasible that the data is loaded once.) But it is good to state this, thank you -- I am adding the comment. – zdim Nov 11 at 4:41

Schwern ,Nov 11 at 4:57

It's bad practice to use require because a future person maintaining the code may also require the same file elsewhere (not even in the same code file, it's per process) and not realize it has already been required. I'd suggest instead explaining why do is the right thing to do here instead of require , it's a necessary complexity. – Schwern Nov 11 at 4:57

zdim ,Nov 11 at 5:40

@Schwern A good point, thank you. Adjusted the post. – zdim Nov 11 at 5:40

zdim ,Nov 13 at 2:15

@DavyM Thank you for kind words. You are right, and there are so many such questions that it even seems more common (than otherwise) when people start out. All that we can do is to keep pointing it out, and write it always in full code examples. – zdim Nov 13 at 2:15

[Nov 16, 2017] Reading/dumping a perl hash from shell

Nov 11, 2017 | stackoverflow.com

newbie ,Nov 11 at 0:27

I have a read-only perl file with a huge hash defined in it. Is there anyway for me to read this perl file and dump out the hash contents?

this is basic structure of the hash within the file.

%hash_name = {
    -files => [
         '<some_path>',
    ],
    -dirs => [
         '<some_path>',
         '<some_path>',
         '<some_path>',
         '<some_path>',
         '<some_path>',
    ],
};

Davy M ,Nov 11 at 0:30

can you not cat the file and redirect it into a one that does have write permissions? cat perl_file_name > new_perl_file_nameDavy M Nov 11 at 0:30

newbie ,Nov 11 at 0:34

yes I did consider that but will go with that approach only if there is no other way to dump the hash without creating a new file. – newbie Nov 11 at 0:34

zdim ,Nov 11 at 2:59

@newbie Thank you, and to repeat the question: Does this file have other Perl code or just this hash? Also, is the hash undeclared (just %hash_name ), as you show it, or is it "lexical," so with my such as: my %hash_name ? – zdim Nov 11 at 2:59

zdim ,Nov 11 at 3:12

@newbie What you show is invalid in Perl: the % in %hash_name indicates that the variable is a hash , but { .. } form a hash reference , which is a scalar variable (not a hash). So it should be either %hash_name = ( .. ) or it's $hashref_name = { .. }zdim Nov 11 at 3:12

Schwern ,Nov 11 at 6:59

Note this is an insecure way to store data. The data file must be evaluated as perl code. Any arbitrary code could be in the file. In addition, the data file can only be read by Perl programs. Instead, use JSON or similar data format. JSON::MaybeXS can convert between JSON and Perl. – Schwern Nov 11 at 6:59

zdim ,Nov 11 at 3:40

Ideally you'd copy the file so that you can edit it, then turn it into a module so to use it nicely.

But if for some reason this isn't feasible here are your options.

If that hash is the only thing in the file , "load" it using do and assign to a hash

use warnings;
use strict;

my $file = './read_this.pl';  # the file has *only* that one hash

my %hash = do $file;

This form of do executes the file (runs it as a script), returning the last expression that is evaluated. With only the hash in the file that last expression is the hash definition, precisely what you need.

If the hash is undeclared , so a global variable (or declared with our ), then declare as our a hash with the same name in your program and again load the file with do

our %hash_name;  # same name as in the file
do $file;        # file has "%hash" or "our %hash" (not "my %hash")

Here we "pick up" the hash that is evaluated as do runs the file by virtues of our

If the hash is "lexical" , declared as my %hash (as it should be!) ... well, this is bad. Then you need to parse the text of the file so to extract lines with the hash. This is in general very hard to do, as it amounts to parsing Perl. (A hash can be built using map , returned from a sub as a reference or a flat list ...) Once that is done you eval the variable which contains the text defining that hash.

However, if you know how the hash is built, as you imply, with no () anywhere inside

use warnings; 
use strict;

my $file = './read_this.pl';

my $content = do {  # "slurp" the file -- read it into a variable
    local $/;
    open my $fh, '<', $file or die "Can't open $file: $!";
    <$fh>;
};

my ($hash_text) = $content =~ /\%hash_name\s*=\s*(\(.*?\)/s;
my %hash = eval $hash_text;

This simple shot leaves out a lot, assuming squarely that the hash is as shown. Also note that this form of eval carries real and serious security risks.


Files are also loaded using require . Apart from it doing a lot more than do , the important thing here is that even if it runs multiple times require still loads that file only once . This matters for modules in the first place, which shouldn't be loaded multiple times, and use indeed uses require .

On the other hand, do does it every time, what makes it suitable for loading files to be used as data, which presumably should be read every time. This is the recommended method. Note that require itself uses do to actually load the file.

Thanks to Schwern for a comment.

Schwern ,Nov 11 at 4:31

do will always load the file. require will only load it once. Since you want to get data from the file, it's recommended to use do . Else the second or third time anything in that process loads the file they'll end up with 1 . – Schwern Nov 11 at 4:31

zdim ,Nov 11 at 4:41

@Schwern Right, thank you for the comment. I wanted to avoid excessive explanation thus I simply use do . (I still mention require since it is feasible that the data is loaded once.) But it is good to state this, thank you -- I am adding the comment. – zdim Nov 11 at 4:41

Schwern ,Nov 11 at 4:57

It's bad practice to use require because a future person maintaining the code may also require the same file elsewhere (not even in the same code file, it's per process) and not realize it has already been required. I'd suggest instead explaining why do is the right thing to do here instead of require , it's a necessary complexity. – Schwern Nov 11 at 4:57

zdim ,Nov 11 at 5:40

@Schwern A good point, thank you. Adjusted the post. – zdim Nov 11 at 5:40

zdim ,Nov 13 at 2:15

@DavyM Thank you for kind words. You are right, and there are so many such questions that it even seems more common (than otherwise) when people start out. All that we can do is to keep pointing it out, and write it always in full code examples. – zdim Nov 13 at 2:15

[Nov 14, 2017] Exporter - search.cpan.org

Nov 14, 2017 | search.cpan.org

Todd Rinaldo > Exporter-5.72 > Exporter

Download:
Exporter-5.72.tar.gz

Dependencies

Annotate this POD

View/Report Bugs
Module Version: 5.72 Source NAME ^

Exporter - Implements default import method for modules

SYNOPSIS ^

In module YourModule.pm :

  package YourModule;
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request

or

  package YourModule;
  use Exporter 'import'; # gives you Exporter's import() method directly
  @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request

In other files which wish to use YourModule :

  use YourModule qw(frobnicate);      # import listed symbols
  frobnicate ($left, $right)          # calls YourModule::frobnicate

Take a look at "Good Practices" for some variants you will like to use in modern Perl code.

DESCRIPTION ^

The Exporter module implements an import method which allows a module to export functions and variables to its users' namespaces. Many modules use Exporter rather than implementing their own import method because Exporter provides a highly flexible interface, with an implementation optimised for the common case.

Perl automatically calls the import method when processing a use statement for a module. Modules and use are documented in perlfunc and perlmod . Understanding the concept of modules and how the use statement operates is important to understanding the Exporter.

How to Export

The arrays @EXPORT and @EXPORT_OK in a module hold lists of symbols that are going to be exported into the users name space by default, or which they can request to be exported, respectively. The symbols can represent functions, scalars, arrays, hashes, or typeglobs. The symbols must be given by full name with the exception that the ampersand in front of a function is optional, e.g.

    @EXPORT    = qw(afunc $scalar @array);   # afunc is a function
    @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc

If you are only exporting function names it is recommended to omit the ampersand, as the implementation is faster this way.

Selecting What to Export

Do not export method names!

Do not export anything else by default without a good reason!

Exports pollute the namespace of the module user. If you must export try to use @EXPORT_OK in preference to @EXPORT and avoid short or common symbol names to reduce the risk of name clashes.

Generally anything not exported is still accessible from outside the module using the YourModule::item_name (or $blessed_ref->method ) syntax. By convention you can use a leading underscore on names to informally indicate that they are 'internal' and not for public use.

(It is actually possible to get private functions by saying:

  my $subref = sub { ... };
  $subref->(@args);            # Call it as a function
  $obj->$subref(@args);        # Use it as a method

However if you use them for methods it is up to you to figure out how to make inheritance work.)

As a general rule, if the module is trying to be object oriented then export nothing. If it's just a collection of functions then @EXPORT_OK anything but use @EXPORT with caution. For function and method names use barewords in preference to names prefixed with ampersands for the export lists.

Other module design guidelines can be found in perlmod .

How to Import

In other files which wish to use your module there are three basic ways for them to load your module and import its symbols:

use YourModule;
This imports all the symbols from YourModule's @EXPORT into the namespace of the use statement.
use YourModule ();
This causes perl to load your module but does not import any symbols.
use YourModule qw(...);
This imports only the symbols listed by the caller into their namespace. All listed symbols must be in your @EXPORT or @EXPORT_OK , else an error occurs. The advanced export features of Exporter are accessed like this, but with list entries that are syntactically distinct from symbol names.

Unless you want to use its advanced features, this is probably all you need to know to use Exporter.

Advanced Features ^ Specialised Import Lists

If any of the entries in an import list begins with !, : or / then the list is treated as a series of specifications which either add to or delete from the list of names to import. They are processed left to right. Specifications are in the form:

    [!]name         This name only
    [!]:DEFAULT     All names in @EXPORT
    [!]:tag         All names in $EXPORT_TAGS{tag} anonymous array
    [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match

A leading ! indicates that matching names should be deleted from the list of names to import. If the first specification is a deletion it is treated as though preceded by :DEFAULT. If you just want to import extra names in addition to the default set you will still need to include :DEFAULT explicitly.

e.g., Module.pm defines:

    @EXPORT      = qw(A1 A2 A3 A4 A5);
    @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
    %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);

Note that you cannot use tags in @EXPORT or @EXPORT_OK.

Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.

An application using Module can say something like:

    use Module qw(:DEFAULT :T2 !B3 A3);

Other examples include:

    use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
    use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);

Remember that most patterns (using //) will need to be anchored with a leading ^, e.g., /^EXIT/ rather than /EXIT/ .

You can say BEGIN { $Exporter::Verbose=1 } to see how the specifications are being processed and what is actually being imported into modules.

Exporting Without Using Exporter's import Method

Exporter has a special method, 'export_to_level' which is used in situations where you can't directly call Exporter's import method. The export_to_level method looks like:

    MyPackage->export_to_level(
        $where_to_export, $package, @what_to_export
    );

where $where_to_export is an integer telling how far up the calling stack to export your symbols, and @what_to_export is an array telling what symbols *to* export (usually this is @_ ). The $package argument is currently unused.

For example, suppose that you have a module, A, which already has an import function:

    package A;

    @ISA = qw(Exporter);
    @EXPORT_OK = qw($b);

    sub import
    {
        $A::b = 1;     # not a very useful import method
    }

and you want to Export symbol $A::b back to the module that called package A. Since Exporter relies on the import method to work, via inheritance, as it stands Exporter::import() will never get called. Instead, say the following:

    package A;
    @ISA = qw(Exporter);
    @EXPORT_OK = qw($b);

    sub import
    {
        $A::b = 1;
        A->export_to_level(1, @_);
    }

This will export the symbols one level 'above' the current package - ie: to the program or module that used package A.

Note: Be careful not to modify @_ at all before you call export_to_level - or people using your package will get very unexplained results!

Exporting Without Inheriting from Exporter

By including Exporter in your @ISA you inherit an Exporter's import() method but you also inherit several other helper methods which you probably don't want. To avoid this you can do:

  package YourModule;
  use Exporter qw(import);

which will export Exporter's own import() method into YourModule. Everything will work as before but you won't need to include Exporter in @YourModule::ISA .

Note: This feature was introduced in version 5.57 of Exporter, released with perl 5.8.3.

Module Version Checking

The Exporter module will convert an attempt to import a number from a module into a call to $module_name->VERSION($value) . This can be used to validate that the version of the module being used is greater than or equal to the required version.

For historical reasons, Exporter supplies a require_version method that simply delegates to VERSION . Originally, before UNIVERSAL::VERSION existed, Exporter would call require_version .

Since the UNIVERSAL::VERSION method treats the $VERSION number as a simple numeric value it will regard version 1.10 as lower than 1.9. For this reason it is strongly recommended that you use numbers with at least two decimal places, e.g., 1.09.

Managing Unknown Symbols

In some situations you may want to prevent certain symbols from being exported. Typically this applies to extensions which have functions or constants that may not exist on some systems.

The names of any symbols that cannot be exported should be listed in the @EXPORT_FAIL array.

If a module attempts to import any of these symbols the Exporter will give the module an opportunity to handle the situation before generating an error. The Exporter will call an export_fail method with a list of the failed symbols:

  @failed_symbols = $module_name->export_fail(@failed_symbols);

If the export_fail method returns an empty list then no error is recorded and all the requested symbols are exported. If the returned list is not empty then an error is generated for each symbol and the export fails. The Exporter provides a default export_fail method which simply returns the list unchanged.

Uses for the export_fail method include giving better error messages for some symbols and performing lazy architectural checks (put more symbols into @EXPORT_FAIL by default and then take them out if someone actually tries to use them and an expensive check shows that they are usable on that platform).

Tag Handling Utility Functions

Since the symbols listed within %EXPORT_TAGS must also appear in either @EXPORT or @EXPORT_OK , two utility functions are provided which allow you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK :

  %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);

  Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
  Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK

Any names which are not tags are added to @EXPORT or @EXPORT_OK unchanged but will trigger a warning (with -w ) to avoid misspelt tags names being silently added to @EXPORT or @EXPORT_OK . Future versions may make this a fatal error.

Generating Combined Tags

If several symbol categories exist in %EXPORT_TAGS , it's usually useful to create the utility ":all" to simplify "use" statements.

The simplest way to do this is:

  %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);

  # add all the other ":class" tags to the ":all" class,
  # deleting duplicates
  {
    my %seen;

    push @{$EXPORT_TAGS{all}},
      grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
  }

CGI.pm creates an ":all" tag which contains some (but not really all) of its categories. That could be done with one small change:

  # add some of the other ":class" tags to the ":all" class,
  # deleting duplicates
  {
    my %seen;

    push @{$EXPORT_TAGS{all}},
      grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
        foreach qw/html2 html3 netscape form cgi internal/;
  }

Note that the tag names in %EXPORT_TAGS don't have the leading ':'.

AUTOLOAD ed Constants

Many modules make use of AUTOLOAD ing for constant subroutines to avoid having to compile and waste memory on rarely used values (see perlsub for details on constant subroutines). Calls to such constant subroutines are not optimized away at compile time because they can't be checked at compile time for constancy.

Even if a prototype is available at compile time, the body of the subroutine is not (it hasn't been AUTOLOAD ed yet). perl needs to examine both the () prototype and the body of a subroutine at compile time to detect that it can safely replace calls to that subroutine with the constant value.

A workaround for this is to call the constants once in a BEGIN block:

   package My ;

   use Socket ;

   foo( SO_LINGER );  ## SO_LINGER NOT optimized away; called at runtime
   BEGIN { SO_LINGER }
   foo( SO_LINGER );  ## SO_LINGER optimized away at compile time.

This forces the AUTOLOAD for SO_LINGER to take place before SO_LINGER is encountered later in My package.

If you are writing a package that AUTOLOAD s, consider forcing an AUTOLOAD for any constants explicitly imported by other packages or which are usually used when your package is use d.

Good Practices ^ Declaring @EXPORT_OK and Friends

When using Exporter with the standard strict and warnings pragmas, the our keyword is needed to declare the package variables @EXPORT_OK , @EXPORT , @ISA , etc.

  our @ISA = qw(Exporter);
  our @EXPORT_OK = qw(munge frobnicate);

If backward compatibility for Perls under 5.6 is important, one must write instead a use vars statement.

  use vars qw(@ISA @EXPORT_OK);
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(munge frobnicate);
Playing Safe

There are some caveats with the use of runtime statements like require Exporter and the assignment to package variables, which can be very subtle for the unaware programmer. This may happen for instance with mutually recursive modules, which are affected by the time the relevant constructions are executed.

The ideal (but a bit ugly) way to never have to think about that is to use BEGIN blocks. So the first part of the "SYNOPSIS" code could be rewritten as:

  package YourModule;

  use strict;
  use warnings;

  our (@ISA, @EXPORT_OK);
  BEGIN {
     require Exporter;
     @ISA = qw(Exporter);
     @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
  }

The BEGIN will assure that the loading of Exporter.pm and the assignments to @ISA and @EXPORT_OK happen immediately, leaving no room for something to get awry or just plain wrong.

With respect to loading Exporter and inheriting, there are alternatives with the use of modules like base and parent .

  use base qw(Exporter);
  # or
  use parent qw(Exporter);

Any of these statements are nice replacements for BEGIN { require Exporter; @ISA = qw(Exporter); } with the same compile-time effect. The basic difference is that base code interacts with declared fields while parent is a streamlined version of the older base code to just establish the IS-A relationship.

For more details, see the documentation and code of base and parent .

Another thorough remedy to that runtime vs. compile-time trap is to use Exporter::Easy , which is a wrapper of Exporter that allows all boilerplate code at a single gulp in the use statement.

   use Exporter::Easy (
       OK => [ qw(munge frobnicate) ],
   );
   # @ISA setup is automatic
   # all assignments happen at compile time
What Not to Export

You have been warned already in "Selecting What to Export" to not export:

There's one more item to add to this list. Do not export variable names. Just because Exporter lets you do that, it does not mean you should.

  @EXPORT_OK = qw($svar @avar %hvar); # DON'T!

Exporting variables is not a good idea. They can change under the hood, provoking horrible effects at-a-distance that are too hard to track and to fix. Trust me: they are not worth it.

To provide the capability to set/get class-wide settings, it is best instead to provide accessors as subroutines or class methods instead.

SEE ALSO ^

Exporter is definitely not the only module with symbol exporter capabilities. At CPAN, you may find a bunch of them. Some are lighter. Some provide improved APIs and features. Pick the one that fits your needs. The following is a sample list of such modules.

    Exporter::Easy
    Exporter::Lite
    Exporter::Renaming
    Exporter::Tidy
    Sub::Exporter / Sub::Installer
    Perl6::Export / Perl6::Export::Attrs
LICENSE ^

This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself.

[Nov 14, 2017] Exporter - search.cpan.org

Nov 14, 2017 | search.cpan.org

Todd Rinaldo > Exporter-5.72 > Exporter

Download:
Exporter-5.72.tar.gz

Dependencies

Annotate this POD

View/Report Bugs
Module Version: 5.72 Source NAME ^

Exporter - Implements default import method for modules

SYNOPSIS ^

In module YourModule.pm :

  package YourModule;
  require Exporter;
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request

or

  package YourModule;
  use Exporter 'import'; # gives you Exporter's import() method directly
  @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request

In other files which wish to use YourModule :

  use YourModule qw(frobnicate);      # import listed symbols
  frobnicate ($left, $right)          # calls YourModule::frobnicate

Take a look at "Good Practices" for some variants you will like to use in modern Perl code.

DESCRIPTION ^

The Exporter module implements an import method which allows a module to export functions and variables to its users' namespaces. Many modules use Exporter rather than implementing their own import method because Exporter provides a highly flexible interface, with an implementation optimised for the common case.

Perl automatically calls the import method when processing a use statement for a module. Modules and use are documented in perlfunc and perlmod . Understanding the concept of modules and how the use statement operates is important to understanding the Exporter.

How to Export

The arrays @EXPORT and @EXPORT_OK in a module hold lists of symbols that are going to be exported into the users name space by default, or which they can request to be exported, respectively. The symbols can represent functions, scalars, arrays, hashes, or typeglobs. The symbols must be given by full name with the exception that the ampersand in front of a function is optional, e.g.

    @EXPORT    = qw(afunc $scalar @array);   # afunc is a function
    @EXPORT_OK = qw(&bfunc %hash *typeglob); # explicit prefix on &bfunc

If you are only exporting function names it is recommended to omit the ampersand, as the implementation is faster this way.

Selecting What to Export

Do not export method names!

Do not export anything else by default without a good reason!

Exports pollute the namespace of the module user. If you must export try to use @EXPORT_OK in preference to @EXPORT and avoid short or common symbol names to reduce the risk of name clashes.

Generally anything not exported is still accessible from outside the module using the YourModule::item_name (or $blessed_ref->method ) syntax. By convention you can use a leading underscore on names to informally indicate that they are 'internal' and not for public use.

(It is actually possible to get private functions by saying:

  my $subref = sub { ... };
  $subref->(@args);            # Call it as a function
  $obj->$subref(@args);        # Use it as a method

However if you use them for methods it is up to you to figure out how to make inheritance work.)

As a general rule, if the module is trying to be object oriented then export nothing. If it's just a collection of functions then @EXPORT_OK anything but use @EXPORT with caution. For function and method names use barewords in preference to names prefixed with ampersands for the export lists.

Other module design guidelines can be found in perlmod .

How to Import

In other files which wish to use your module there are three basic ways for them to load your module and import its symbols:

use YourModule;
This imports all the symbols from YourModule's @EXPORT into the namespace of the use statement.
use YourModule ();
This causes perl to load your module but does not import any symbols.
use YourModule qw(...);
This imports only the symbols listed by the caller into their namespace. All listed symbols must be in your @EXPORT or @EXPORT_OK , else an error occurs. The advanced export features of Exporter are accessed like this, but with list entries that are syntactically distinct from symbol names.

Unless you want to use its advanced features, this is probably all you need to know to use Exporter.

Advanced Features ^ Specialised Import Lists

If any of the entries in an import list begins with !, : or / then the list is treated as a series of specifications which either add to or delete from the list of names to import. They are processed left to right. Specifications are in the form:

    [!]name         This name only
    [!]:DEFAULT     All names in @EXPORT
    [!]:tag         All names in $EXPORT_TAGS{tag} anonymous array
    [!]/pattern/    All names in @EXPORT and @EXPORT_OK which match

A leading ! indicates that matching names should be deleted from the list of names to import. If the first specification is a deletion it is treated as though preceded by :DEFAULT. If you just want to import extra names in addition to the default set you will still need to include :DEFAULT explicitly.

e.g., Module.pm defines:

    @EXPORT      = qw(A1 A2 A3 A4 A5);
    @EXPORT_OK   = qw(B1 B2 B3 B4 B5);
    %EXPORT_TAGS = (T1 => [qw(A1 A2 B1 B2)], T2 => [qw(A1 A2 B3 B4)]);

Note that you cannot use tags in @EXPORT or @EXPORT_OK.

Names in EXPORT_TAGS must also appear in @EXPORT or @EXPORT_OK.

An application using Module can say something like:

    use Module qw(:DEFAULT :T2 !B3 A3);

Other examples include:

    use Socket qw(!/^[AP]F_/ !SOMAXCONN !SOL_SOCKET);
    use POSIX  qw(:errno_h :termios_h !TCSADRAIN !/^EXIT/);

Remember that most patterns (using //) will need to be anchored with a leading ^, e.g., /^EXIT/ rather than /EXIT/ .

You can say BEGIN { $Exporter::Verbose=1 } to see how the specifications are being processed and what is actually being imported into modules.

Exporting Without Using Exporter's import Method

Exporter has a special method, 'export_to_level' which is used in situations where you can't directly call Exporter's import method. The export_to_level method looks like:

    MyPackage->export_to_level(
        $where_to_export, $package, @what_to_export
    );

where $where_to_export is an integer telling how far up the calling stack to export your symbols, and @what_to_export is an array telling what symbols *to* export (usually this is @_ ). The $package argument is currently unused.

For example, suppose that you have a module, A, which already has an import function:

    package A;

    @ISA = qw(Exporter);
    @EXPORT_OK = qw($b);

    sub import
    {
        $A::b = 1;     # not a very useful import method
    }

and you want to Export symbol $A::b back to the module that called package A. Since Exporter relies on the import method to work, via inheritance, as it stands Exporter::import() will never get called. Instead, say the following:

    package A;
    @ISA = qw(Exporter);
    @EXPORT_OK = qw($b);

    sub import
    {
        $A::b = 1;
        A->export_to_level(1, @_);
    }

This will export the symbols one level 'above' the current package - ie: to the program or module that used package A.

Note: Be careful not to modify @_ at all before you call export_to_level - or people using your package will get very unexplained results!

Exporting Without Inheriting from Exporter

By including Exporter in your @ISA you inherit an Exporter's import() method but you also inherit several other helper methods which you probably don't want. To avoid this you can do:

  package YourModule;
  use Exporter qw(import);

which will export Exporter's own import() method into YourModule. Everything will work as before but you won't need to include Exporter in @YourModule::ISA .

Note: This feature was introduced in version 5.57 of Exporter, released with perl 5.8.3.

Module Version Checking

The Exporter module will convert an attempt to import a number from a module into a call to $module_name->VERSION($value) . This can be used to validate that the version of the module being used is greater than or equal to the required version.

For historical reasons, Exporter supplies a require_version method that simply delegates to VERSION . Originally, before UNIVERSAL::VERSION existed, Exporter would call require_version .

Since the UNIVERSAL::VERSION method treats the $VERSION number as a simple numeric value it will regard version 1.10 as lower than 1.9. For this reason it is strongly recommended that you use numbers with at least two decimal places, e.g., 1.09.

Managing Unknown Symbols

In some situations you may want to prevent certain symbols from being exported. Typically this applies to extensions which have functions or constants that may not exist on some systems.

The names of any symbols that cannot be exported should be listed in the @EXPORT_FAIL array.

If a module attempts to import any of these symbols the Exporter will give the module an opportunity to handle the situation before generating an error. The Exporter will call an export_fail method with a list of the failed symbols:

  @failed_symbols = $module_name->export_fail(@failed_symbols);

If the export_fail method returns an empty list then no error is recorded and all the requested symbols are exported. If the returned list is not empty then an error is generated for each symbol and the export fails. The Exporter provides a default export_fail method which simply returns the list unchanged.

Uses for the export_fail method include giving better error messages for some symbols and performing lazy architectural checks (put more symbols into @EXPORT_FAIL by default and then take them out if someone actually tries to use them and an expensive check shows that they are usable on that platform).

Tag Handling Utility Functions

Since the symbols listed within %EXPORT_TAGS must also appear in either @EXPORT or @EXPORT_OK , two utility functions are provided which allow you to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK :

  %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);

  Exporter::export_tags('foo');     # add aa, bb and cc to @EXPORT
  Exporter::export_ok_tags('bar');  # add aa, cc and dd to @EXPORT_OK

Any names which are not tags are added to @EXPORT or @EXPORT_OK unchanged but will trigger a warning (with -w ) to avoid misspelt tags names being silently added to @EXPORT or @EXPORT_OK . Future versions may make this a fatal error.

Generating Combined Tags

If several symbol categories exist in %EXPORT_TAGS , it's usually useful to create the utility ":all" to simplify "use" statements.

The simplest way to do this is:

  %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);

  # add all the other ":class" tags to the ":all" class,
  # deleting duplicates
  {
    my %seen;

    push @{$EXPORT_TAGS{all}},
      grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;
  }

CGI.pm creates an ":all" tag which contains some (but not really all) of its categories. That could be done with one small change:

  # add some of the other ":class" tags to the ":all" class,
  # deleting duplicates
  {
    my %seen;

    push @{$EXPORT_TAGS{all}},
      grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}
        foreach qw/html2 html3 netscape form cgi internal/;
  }

Note that the tag names in %EXPORT_TAGS don't have the leading ':'.

AUTOLOAD ed Constants

Many modules make use of AUTOLOAD ing for constant subroutines to avoid having to compile and waste memory on rarely used values (see perlsub for details on constant subroutines). Calls to such constant subroutines are not optimized away at compile time because they can't be checked at compile time for constancy.

Even if a prototype is available at compile time, the body of the subroutine is not (it hasn't been AUTOLOAD ed yet). perl needs to examine both the () prototype and the body of a subroutine at compile time to detect that it can safely replace calls to that subroutine with the constant value.

A workaround for this is to call the constants once in a BEGIN block:

   package My ;

   use Socket ;

   foo( SO_LINGER );  ## SO_LINGER NOT optimized away; called at runtime
   BEGIN { SO_LINGER }
   foo( SO_LINGER );  ## SO_LINGER optimized away at compile time.

This forces the AUTOLOAD for SO_LINGER to take place before SO_LINGER is encountered later in My package.

If you are writing a package that AUTOLOAD s, consider forcing an AUTOLOAD for any constants explicitly imported by other packages or which are usually used when your package is use d.

Good Practices ^ Declaring @EXPORT_OK and Friends

When using Exporter with the standard strict and warnings pragmas, the our keyword is needed to declare the package variables @EXPORT_OK , @EXPORT , @ISA , etc.

  our @ISA = qw(Exporter);
  our @EXPORT_OK = qw(munge frobnicate);

If backward compatibility for Perls under 5.6 is important, one must write instead a use vars statement.

  use vars qw(@ISA @EXPORT_OK);
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(munge frobnicate);
Playing Safe

There are some caveats with the use of runtime statements like require Exporter and the assignment to package variables, which can be very subtle for the unaware programmer. This may happen for instance with mutually recursive modules, which are affected by the time the relevant constructions are executed.

The ideal (but a bit ugly) way to never have to think about that is to use BEGIN blocks. So the first part of the "SYNOPSIS" code could be rewritten as:

  package YourModule;

  use strict;
  use warnings;

  our (@ISA, @EXPORT_OK);
  BEGIN {
     require Exporter;
     @ISA = qw(Exporter);
     @EXPORT_OK = qw(munge frobnicate);  # symbols to export on request
  }

The BEGIN will assure that the loading of Exporter.pm and the assignments to @ISA and @EXPORT_OK happen immediately, leaving no room for something to get awry or just plain wrong.

With respect to loading Exporter and inheriting, there are alternatives with the use of modules like base and parent .

  use base qw(Exporter);
  # or
  use parent qw(Exporter);

Any of these statements are nice replacements for BEGIN { require Exporter; @ISA = qw(Exporter); } with the same compile-time effect. The basic difference is that base code interacts with declared fields while parent is a streamlined version of the older base code to just establish the IS-A relationship.

For more details, see the documentation and code of base and parent .

Another thorough remedy to that runtime vs. compile-time trap is to use Exporter::Easy , which is a wrapper of Exporter that allows all boilerplate code at a single gulp in the use statement.

   use Exporter::Easy (
       OK => [ qw(munge frobnicate) ],
   );
   # @ISA setup is automatic
   # all assignments happen at compile time
What Not to Export

You have been warned already in "Selecting What to Export" to not export:

There's one more item to add to this list. Do not export variable names. Just because Exporter lets you do that, it does not mean you should.

  @EXPORT_OK = qw($svar @avar %hvar); # DON'T!

Exporting variables is not a good idea. They can change under the hood, provoking horrible effects at-a-distance that are too hard to track and to fix. Trust me: they are not worth it.

To provide the capability to set/get class-wide settings, it is best instead to provide accessors as subroutines or class methods instead.

SEE ALSO ^

Exporter is definitely not the only module with symbol exporter capabilities. At CPAN, you may find a bunch of them. Some are lighter. Some provide improved APIs and features. Pick the one that fits your needs. The following is a sample list of such modules.

    Exporter::Easy
    Exporter::Lite
    Exporter::Renaming
    Exporter::Tidy
    Sub::Exporter / Sub::Installer
    Perl6::Export / Perl6::Export::Attrs
LICENSE ^

This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself.

[Nov 13, 2017] Perl for Newbies - Part 3 by Shlomi Fish

Nov 13, 2017 | perl-begin.org

Perl Modules

Perl modules are namespaces that contain function and variables. Two distinct modules may each contain a function (or a variable) with the same name, yet the perl interpreter will be able to tell them apart. Furthermore, both functions can be invoked from the same code.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDeclaring a Package 3.1. Declaring a Package

In order to designate that a code belongs to a different namespace you should use the package directive. For instance, if you want your module name to be "MyModule" your file should look something like this:

# This is the file MyModule.pm
#

package MyModule;

use strict;
use warnings;

sub a_function
{
    print "Hello, World!\n";
}

1;

Note that a module has to return a true value to the perl interpreter, which explains the use of "1;".

A namespace may contain sub-namespaces. To separate namespace components, use the :: separator. For example:

# This is the file Hoola/Hoop.pm
#

package Hoola::Hoop;

use strict;
use warnings;

my $counter = 0;

sub get_counter
{
    return $counter++;
}

1;

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDeclaring a Package Where to find a module 3.1.1. Where to find a module

A module is a separate file that may contain one or more different namespaces. That file is found in a place that corresponds to the module's name. To find the filename of the module relative to the script's directory, replace every :: with a slash and add ".pm" to the name of the last component.

For instance: the MyModule module will be found in the file "MyModule.pm"; the Hello::World module will be found in the file "World.pm" under the Hello sub-directory; etc.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions 3.2. Loading Modules and Importing their Functions

In order to have access to a module from within your script (or from within another module) you can use the use directive followed by the name of the module as it is deduced from its path. Here's an example: assume that the file "MyModule.pm" is this:

# This is the file MyModule.pm
#

package MyModule;

use strict;
use warnings;

sub a_function
{
    print "Hello, World!\n";
}

1;

And this is your script:

#!/usr/bin/perl

use strict;
use warnings;

use MyModule;

# Notice that we use "::" to call the function out of the module.
MyModule::a_function();

That way, the program will print "Hello, World!" on the screen.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Accessing Functions from a Different Module 3.2.1. Accessing Functions from a Different Module

As could be seen from the last example, once the module has been use 'd, its functions can be invoked by typing the full path of the package followed by :: and followed by the function name.

Note that if you are in package Foo and you are trying to access functions from package Foo::Bar , then typing Bar::my_func() will not do. You have to type the full path of the module. ( Foo::Bar::my_func() in our case)


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Exporting and Importing Functions 3.2.2. Exporting and Importing Functions

It is possible to make a functions of your module automatically available in any other namespace or script that uses it. To do so one needs to type the following code fragment near the beginning of the module:

use Exporter;

use vars qw(@ISA @EXPORT);

@ISA=qw(Exporter);

@EXPORT=("function1", "function2", "function3");

What this fragment does is make the module inherit the Exporter module which is a special Perl module that can export symbols. Then it declares the special variable @EXPORT which should be filled with all the functions that one wishes to export.

Here is an example which has a module called "Calc" and a script that uses it:

# File: Calc.pm
#
package Calc;

use strict;
use warnings;

use Exporter;

use vars qw(@ISA @EXPORT);

@ISA=qw(Exporter);

@EXPORT=("gcd");

# This function calculates the greatest common divisor of two integers
sub gcd
{
    my $m = shift;
    my $n = shift;

    if ($n > $m)
    {
        ($m, $n) = ($n , $m);
    }

    while ($m % $n > 0)
    {
        ($m, $n) = ($n, $m % $n);
    }

    return $n;
}

1;
#!/usr/bin/perl

use strict;
use warnings;

use Calc;

my $m = 200;
my $n = 15;

print "gcd($m,$n) == " , gcd($m,$n), "\n";

As you can see, the script invokes the "gcd" function of the "Calc" module without having to invoke it with Calc::gcd() . Exporting functions like that should be used with care, as the function names may conflict with those of the importing namespace.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Using Variables from a Different Namespace 3.2.3. Using Variables from a Different Namespace

It is also possible to use the global variables of different packages. However, such variables need to be declared using the use vars qw($myvar1 @myvar2) construct.

Here's an example for a module that defines a variable and another one that access it:

# This file is MyVar.pm
#
package MyVar;

use strict;
use warnings;

# Declare a namespace-scoped variable named $myvar.
use vars qw($myvar);

sub print_myvar
{
    print $myvar, "\n";
}

1;
#!/usr/bin/perl

use strict;
use warnings;

use MyVar;

$MyVar::myvar = "Hello";

MyVar::print_myvar();

$MyVar::myvar = "World";

MyVar::print_myvar();

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesBEGIN and END 3.3. BEGIN and END

There are two special code blocks for perl modules - BEGIN and END . These blocks are executed when a module is first loaded, and when the perl interpreter is about to unload it, respectively.

Here's an example for a logging module that makes use of this facility:

# File : MyLog.pm
#

package MyLog;

use strict;
use warnings;

BEGIN
{
    open MYLOG, ">", "mylog.txt";
}

sub log
{
    my $what = shift;

    # Strip the string of newline characters
    $what =~ s/\n//g;

    # The MYLOG filehandle is already open by virtue of the BEGIN
    # block.
    print MYLOG $what, "\n";
}

END
{
    close(MYLOG);
}

1;

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesThe "main" Namespace 3.4. The "main" Namespace

One can access the main namespace (i.e, the namespace of the script), from any other namespace by designating main as the namespace path. For instance, main::hello() will invoke the function named "hello" in the script file.

Usually, the "main" part can be omitted and the symbols be accessed with the notation of ::hello() alone.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDifference between Namespaces and Modules 3.5. Difference between Namespaces and Modules

[Nov 13, 2017] Perl for Newbies - Part 3 by Shlomi Fish

Nov 13, 2017 | perl-begin.org

Perl Modules

Perl modules are namespaces that contain function and variables. Two distinct modules may each contain a function (or a variable) with the same name, yet the perl interpreter will be able to tell them apart. Furthermore, both functions can be invoked from the same code.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDeclaring a Package 3.1. Declaring a Package

In order to designate that a code belongs to a different namespace you should use the package directive. For instance, if you want your module name to be "MyModule" your file should look something like this:

# This is the file MyModule.pm
#

package MyModule;

use strict;
use warnings;

sub a_function
{
    print "Hello, World!\n";
}

1;

Note that a module has to return a true value to the perl interpreter, which explains the use of "1;".

A namespace may contain sub-namespaces. To separate namespace components, use the :: separator. For example:

# This is the file Hoola/Hoop.pm
#

package Hoola::Hoop;

use strict;
use warnings;

my $counter = 0;

sub get_counter
{
    return $counter++;
}

1;

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDeclaring a Package Where to find a module 3.1.1. Where to find a module

A module is a separate file that may contain one or more different namespaces. That file is found in a place that corresponds to the module's name. To find the filename of the module relative to the script's directory, replace every :: with a slash and add ".pm" to the name of the last component.

For instance: the MyModule module will be found in the file "MyModule.pm"; the Hello::World module will be found in the file "World.pm" under the Hello sub-directory; etc.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions 3.2. Loading Modules and Importing their Functions

In order to have access to a module from within your script (or from within another module) you can use the use directive followed by the name of the module as it is deduced from its path. Here's an example: assume that the file "MyModule.pm" is this:

# This is the file MyModule.pm
#

package MyModule;

use strict;
use warnings;

sub a_function
{
    print "Hello, World!\n";
}

1;

And this is your script:

#!/usr/bin/perl

use strict;
use warnings;

use MyModule;

# Notice that we use "::" to call the function out of the module.
MyModule::a_function();

That way, the program will print "Hello, World!" on the screen.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Accessing Functions from a Different Module 3.2.1. Accessing Functions from a Different Module

As could be seen from the last example, once the module has been use 'd, its functions can be invoked by typing the full path of the package followed by :: and followed by the function name.

Note that if you are in package Foo and you are trying to access functions from package Foo::Bar , then typing Bar::my_func() will not do. You have to type the full path of the module. ( Foo::Bar::my_func() in our case)


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Exporting and Importing Functions 3.2.2. Exporting and Importing Functions

It is possible to make a functions of your module automatically available in any other namespace or script that uses it. To do so one needs to type the following code fragment near the beginning of the module:

use Exporter;

use vars qw(@ISA @EXPORT);

@ISA=qw(Exporter);

@EXPORT=("function1", "function2", "function3");

What this fragment does is make the module inherit the Exporter module which is a special Perl module that can export symbols. Then it declares the special variable @EXPORT which should be filled with all the functions that one wishes to export.

Here is an example which has a module called "Calc" and a script that uses it:

# File: Calc.pm
#
package Calc;

use strict;
use warnings;

use Exporter;

use vars qw(@ISA @EXPORT);

@ISA=qw(Exporter);

@EXPORT=("gcd");

# This function calculates the greatest common divisor of two integers
sub gcd
{
    my $m = shift;
    my $n = shift;

    if ($n > $m)
    {
        ($m, $n) = ($n , $m);
    }

    while ($m % $n > 0)
    {
        ($m, $n) = ($n, $m % $n);
    }

    return $n;
}

1;
#!/usr/bin/perl

use strict;
use warnings;

use Calc;

my $m = 200;
my $n = 15;

print "gcd($m,$n) == " , gcd($m,$n), "\n";

As you can see, the script invokes the "gcd" function of the "Calc" module without having to invoke it with Calc::gcd() . Exporting functions like that should be used with care, as the function names may conflict with those of the importing namespace.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesLoading Modules and Importing their Functions Using Variables from a Different Namespace 3.2.3. Using Variables from a Different Namespace

It is also possible to use the global variables of different packages. However, such variables need to be declared using the use vars qw($myvar1 @myvar2) construct.

Here's an example for a module that defines a variable and another one that access it:

# This file is MyVar.pm
#
package MyVar;

use strict;
use warnings;

# Declare a namespace-scoped variable named $myvar.
use vars qw($myvar);

sub print_myvar
{
    print $myvar, "\n";
}

1;
#!/usr/bin/perl

use strict;
use warnings;

use MyVar;

$MyVar::myvar = "Hello";

MyVar::print_myvar();

$MyVar::myvar = "World";

MyVar::print_myvar();

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesBEGIN and END 3.3. BEGIN and END

There are two special code blocks for perl modules - BEGIN and END . These blocks are executed when a module is first loaded, and when the perl interpreter is about to unload it, respectively.

Here's an example for a logging module that makes use of this facility:

# File : MyLog.pm
#

package MyLog;

use strict;
use warnings;

BEGIN
{
    open MYLOG, ">", "mylog.txt";
}

sub log
{
    my $what = shift;

    # Strip the string of newline characters
    $what =~ s/\n//g;

    # The MYLOG filehandle is already open by virtue of the BEGIN
    # block.
    print MYLOG $what, "\n";
}

END
{
    close(MYLOG);
}

1;

Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesThe "main" Namespace 3.4. The "main" Namespace

One can access the main namespace (i.e, the namespace of the script), from any other namespace by designating main as the namespace path. For instance, main::hello() will invoke the function named "hello" in the script file.

Usually, the "main" part can be omitted and the symbols be accessed with the notation of ::hello() alone.


Contents Up Prev Next
Perl for Newbies - Part 3 - Modules and ObjectsPerl ModulesDifference between Namespaces and Modules 3.5. Difference between Namespaces and Modules

Reference

Man Pages:
perlmod Perl modules (packages and symbol tables)
perlref Perl references and nested data structures
perlobj Perl objects
perltoot Tom's object-oriented tutorial for perl
perlbot Bag'o Object Tricks (advanced stuff)

Websites:

genome-www.stanford.edu/perlOOP A little collection I put together as I was learning Object-oriented Perl programming. See especially the examples page.
www.perl.com/CPAN/CPAN.html CPAN homepage
search.cpan.org Search CPAN for a module by author, category, or module name
bioperl.org The Bioperl project - modules for bioinformatics


Etc

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes.   If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner. 

ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.  

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least


Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

Last updated: December 01, 2017