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

Thomas Owens picture Thomas Owens · Nov 17, 2009 · Viewed 15.6k times · Source

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?

Answer

draegtun picture draegtun · Nov 17, 2009

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' );