Your idea seems to capture the spirit of the best suggestions in this thread well.

I was thinking a little more about it and came up with this::

use constant ATTACK_TYPES => [ { type => 'light', damage => 1, speed => 5, }, { type => 'fast', damage => 1, speed => 7, }, { type => 'heavy', damage => 2, speed => 4, }, ]; foreach my $attack ( @{ATTACK_TYPES()} ) { my $name = "new_$attack->{type}"; { no strict 'refs'; *{$name} = sub { return shift->new(%$attack) }; } }

Which seems too clever on the one hand, but on the other hand does a nice job of separating configuration data from code. The fact that it mostly eliminates the pitfalls of "Don't Repeat Yourself" is a bonus. But the real advantage is what can come next: The next logical step would be to store the attack types as a JSON file, and then process it like this:

use IO::All; use JSON 'decode_json'; use constant ATTACK_PARAMS => [ qw/ type damage speed / ]; my $attack_types = decode_json( io('attacks.json')->slurp ); foreach my $attack ( @$attack_types ) { exists $attack->{$_} or die "Malformed attack type: $_\n" for @{ATTACK_PARAMS()}; my $name = "new_$attack->{type}"; { no strict 'refs'; *{$name} = sub { return shift->new(@{$attack}{ATTACK_PARAMS()} +) }; } }

And now someone who doesn't care to learn a lot about programming could still manipulate the game's parameters without wasting your time.


Dave


In reply to Re^2: Convenient Constructors - a Moo question by davido
in thread Convenient Constructors - a Moo question by blindluke

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.