v_melnik has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I have a Moose-class based on the Throwable superclass, let's call it MonkeyMan::Error.

I'd like to create a bunch of subclasses based on MonkeyMan::Error, such as MonkeyMan::Error::Unrecoverable, MonkeyMan::Error::Unrecoverable::BrainDamage and so on, but I don't want to create all these packages manually.

Can I initialize all these subclasses by some Moose-magic inside of the MonkeyMan::Error class?

Thank you!

V.Melnik

Replies are listed 'Best First'.
Re: Moose: creating sub-classes on the fly
by tobyink (Canon) on Oct 10, 2014 at 16:02 UTC

    Yes. Play around with this:

    use v5.14; use warnings; package MonkeyMan::Error { use Moose; my @subclasses = qw( Unrecoverable Unrecoverable::BrainDamage ); for my $stem (@subclasses) { my $subclass = join "::" => (__PACKAGE__, $stem); my $parent = ($subclass =~ s/::\w+$//r); warn "Creating $subclass with parent $parent\n"; Moose::Meta::Class->create( $subclass => ( superclasses => [ $parent ] ), ); } } my $err = MonkeyMan::Error::Unrecoverable::BrainDamage->new; print $err->dump;
Re: Moose: creating sub-classes on the fly
by ikegami (Patriarch) on Oct 10, 2014 at 16:02 UTC
    for my $error_type (qw( Unrecoverable Unrecoverable::BrainDamage )) { eval(" package MonkeyMan::Error::$error_type; our \@ISA = 'MonkeyMan::Error'; 1 ") or die $@; }

      I'm really interested in the question whether this straight forward solution builds up all the metaclass stuff of Moose based classes?

      Best regards
      McA

        Well, I guess that depends on how the inherited meta behaves. If you want to be sure to have all that overhead, you could use
        for my $error_type (qw( Unrecoverable Unrecoverable::BrainDamage )) { eval(" package MonkeyMan::Error::$error_type; use Moose; extends 'MonkeyMan::Error'; 1 ") or die $@; }