Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how do I put multiple packages in a single .pm file?

I'm pretty sure that I read somewhere that it's possible, but there are a few gotchas that you need to be aware of. Unfortunately, I can't find the tutorial or page that described what you need to do. I looked through the Perl tutorials, and didn't find the one that I remember reading. Could someone point me to a page or document that describes how to put multiple packages into a single .pm file?

like image 882
Thomas Owens Avatar asked Nov 17 '09 13:11

Thomas Owens


People also ask

What are .pm files in Perl?

pm file, similar to Java and C# where you can have multiple classes in a single file. A module is a . pm file (“pm” means Perl Module). When you import a module with “require” or “use”, you are literally referencing the file name and not the package(s) contained in the file.

What is package in Perl script?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.

How do you refer variable within a package in Perl?

You can explicitly refer to variables within a package using the :: package qualifier.


2 Answers

This is how I normally do it:

use strict; use warnings; use 5.010;  {     package A;     sub new   { my $class = shift; bless \$class => $class }     sub hello { say 'hello from A' } }  {     package B;     use Data::Dumper;     sub new   { my $class = shift; bless { @_ } => $class }     sub hello { say 'Hello from B + ' . shift->dump       }     sub dump  { Dumper $_[0] } }  $_->hello for A->new, B->new( foo => 'bar' ); 
like image 185
draegtun Avatar answered Oct 05 '22 04:10

draegtun


You simply start off the new package with another package statement:

package PackageOne;  # ...... code  package PackageTwo;  # .... more code 

Problems with this approach (archived on 2009)

like image 29
ennuikiller Avatar answered Oct 05 '22 05:10

ennuikiller