Main Content

Packages in packages in Perl

Archive - Originally posted on "The Horse's Mouth" - 2005-12-16 20:40:31 - Graham Ellis

In perl, all your variables (except "my" ones, which we'll leave for another day) are arranged into packages, and by default that's a package called "main". So if you write about a scalar called $jeremy, that's really $main::jeremy and if you write about a named block of code called &mary, that's really &main::mary.

Why?

So that, as your programs grow, you can arrange all the variables and pieces of code into their own uniquely named modules. That then allows you to use the same name several times over without a conflict.

Good news - but it doesn't go far enough so far; what I've described only goes one level further and module files (for example) would all end up in a single massive "pancake" directory. So the :: notation can be nested, and package namespaces can be nested within package namespaces. As far as file organisation is concerned, you'll be working with a directory structure. This sort of thing is very much used on the CPAN, from where you can download modules such as Net::FTP - to be found once installed in a file called FTP.pm in the Net directory.

Here's an example program and some modules that show this in action.

$ perl pk2lev
tutor
designer
beauty therapist
$

And the pk2lev program:

use ellis::graham;
use ellis::lisa;
use whelan::lisa;
print ellis::graham::job();
print ellis::lisa::job();
print whelan::lisa::job();

The directory structure:

$ ls ellis whelan pk2lev
pk2lev

ellis:
graham.pm lisa.pm

whelan:
lisa.pm
$

And a sample module file:

$ cat ellis/lisa.pm

package ellis::lisa;
sub job {
return "designer\n";
}

1;
$