Perl – Getting Package Names

Had an interesting question from a student i’ve been helping with a project. They were after the package name, for various reasons, and so I prepared a small example with 3 ways of doing 2 things. Heres the example:

use strict;
use warnings;

use 5.020;

{
  package Role::PrintClass;

  use Moo::Role;

  requires 'class_name';

  sub print_class {
    my $self = shift;
    say "Class: " . $self->class_name;
    my @split_class = split ( '::', $self->class_name );
    say "Parts: " . $_ for @split_class;
  }

  sub print_ref {
    my $self = shift;

    say ref($self);
  }
}

{
  package My::Class::A;

  use Moo;

  sub class_name { return __PACKAGE__ };

  with 'Role::PrintClass';
}

{
  package My::Class::B;

  use Moo;

  sub class_name { return __PACKAGE__ };

  with 'Role::PrintClass';
}

my $a = My::Class::A->new;

my $b = My::Class::B->new;

say "Package A";
$a->print_class;
$a->print_ref;
say "$a";
say ref($a);

say "Package B";
$b->print_class;
$b->print_ref;

say "$b";
say ref($b);

The two main ways here, are with the __PACKAGE__ token, or using the ref function.

This also has an example of using Moo::Roles, and some of the basic things you can do with them.

Hopefully this is useful for people!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.