Can anyone recommend any ways of cleaning this up? Is there a more elegant way of doing what I am trying to do? Without using BEGIN blocks and a global hash perhaps? Or without breaking any strictures?
What I'd do is let each animal declare what sound it made...
{ package Animal;
use Carp qw( croak );
sub new { bless \my $scalar, shift };
}
{ package Sheep; use base 'Animal'; sub makes_sound { "baa" } }
{ package Cow; use base 'Animal'; sub makes_sound { "moo" } }
{ package Pig; use base 'Animal'; sub makes_sound { "oink" } }
then introspected the class hierarchy to find the animals that did what I wanted
use Devel::Symdump;
sub make_animal {
my $sound = shift;
my @animals_that_make_sound
= grep { eval { $_->isa( 'Animal' ) && $_->makes_sound eq $sou
+nd } }
Devel::Symdump->rnew->packages;
die "more than one animal can $sound\n" if @animals_that_make_soun
+d > 1;
die "no animals $sound\n" unless @animals_that_make_sound;
return $animals_that_make_sound[0]->new;
}
print make_animal( 'oink' );
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|