Bootstrap FreeKB - Perl (Scripting) - Create your own module
Perl (Scripting) - Create your own module

Updated:   |  Perl (Scripting) articles

A custom module can be created for code that needs to be used in numerous Perl scripts. As a sort of silly but easy example, let's say you want to print a welcome message at the beginning of each of your Perl scripts. First, create a module. A Perl module is a file that ends with the .pm extension, which I suspect is the abbreviation for perl module.

~]# touch /usr/share/perl/modules/foo.pm

 

In the module, add your welcome message, such as "Welcome to my Perl script."

#!/usr/bin/perl
print "Welcome to my Perl script\n";

 

Here is how you would use the module.

#!/usr/bin/perl
use strict;
use warnings;
use lib "/usr/share/perl/modules";
use foo;

 

Now, when running your Perl modules, "Welcome to my Perl script" will be printed to the console.

If something is not working as expected, add the following to your Perl script to validate that the directory that contains your module is included.

print join ( "\n", @INC );

 


Shared Subroutines

As a bit of a more practical example, more often, shared variables or subroutines are placed in a module. For example, let's say you have a module named sharedSubroutines.pm.

/usr/share/perl/modules/sharedSubroutines.pm

 

The sharedSubroutines.pm module would probably look something like this. The package keyword is used to scope the subroutines in the sharedSubroutines.pm module to the package named sharedSubroutines. 

#!/usr/bin/perl
use strict;
use warnings;
package sharedSubroutines;

sub example {
  our $foo = "Hello World";
  return $foo;
}

1;

 

Then, in one of your Perl scripts, you could have something like this, which uses the subroutine named "example" in the Foo package.

#!/usr/bin/perl
use strict;
use warnings;
use Foo;

my $test = Foo::example();
print "\$test = $test\n";

 

Which should return the following.

$test = Hello World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 883938 in the box below so that we can be sure you are a human.