Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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' );

In reply to Re: Factory Pattern by adrianh
in thread Factory Pattern by tomazos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-24 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found