In Perl, how do I put multiple packages in a single .pm file?
-
20-09-2019 - |
Question
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?
Solution
You simply start off the new package with another package statement:
package PackageOne;
# ...... code
package PackageTwo;
# .... more code
OTHER TIPS
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' );
This is what worked for me:
#!/usr/bin/perl
use strict;
use warnings;
{
package A;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(a_sub);
our @EXPORT = qw(a_sub);
sub a_sub {
# your code ...
}
}
{
package B;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(b_sub);
our @EXPORT = qw(b_sub);
sub b_sub {
# your code ...
}
}
# Main code starts here ##############
use boolean;
use Data::Dumper;
import A qw(a_sub);
import B qw(b_sub);
a_sub();
b_sub();
The important point is that instead of using "use", you change it for "import" (that way it won't go and try to look for the file).
How to do it: just issue multiple package
instructions.
Gotchas I can think of: my
-variables aren't package-localized, so they're shared anyway. Before you issue any, you're in package main
by default.