Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Your Very Own Module

You too can write your own modules. It is easy. First, we will create the fantastic bit of code that we want to re-use everywhere. First, we'll write a normal Perl program:

$name=shift;

print &logname($name);

sub logname {
	my $name=shift;
	my @namebits;
	my ($logon,$inital);
	@namebits=split /\s+/,$name;
	($inital)=$name=~/(\w)/;
	$logon=$inital.$namebits[$#namebits];
	$logon=lc $logon;
	return $logon;
}

Execute like so; perl script.pl "Nick Bladon"

The script itself is nothing amazing. The lc function stands for LowerCase, or probably lOWERcASE -- you can see what it does.

In order to turn it into a module carry out the following steps:

  1. Find out where your copy of Perl is installed, for example c:\progs\perl.
  2. Within that directory there should be a lib directory.
  3. Make a directory within lib, for example c:\progs\perl\lib\RMP\

Now we'll make the module. Remember, a module is just code you are going to reuse. So we don't need all of the above example. Just this bit:

sub logname {
        my $name=shift;
        my @namebits;
        my ($logon,$inital);
        @namebits=split /\s+/,$name;
        ($inital)=$name=~/(\w)/;
        $logon=$inital.$namebits[$#namebits];
        $logon=lc $logon;
        return $logon;
}

1;

The bit that has been added is the 1 at the bottom. Why? Perl requires that all modules return true. We know that a subroutine always returns the value of the last expression evaluated. As 1 evaluates to true, that'll do.

You need to save this as logon.pm in your newly created directory under lib. The pm stands for Perl Module.

That's it. A module created. To use, just make a normal Perl script such as:

use RMP::logon;

$name=shift;

print logname($name);

and hey presto! Module power is yours!

You don't have to create your own subdirectory within lib but I would advise it for the sake of neatness. And as you might expect, there is a lot more to learn about modules but this is supposed to be a basic tutorial, so that's enough for the time being.