Unless you absolutely positively want exactly that internal data structure, you can solve the general problem with speed and elegance by using one of the Class::Accessor modules.

That gives you a mature, extensible and (in my opinion) well-designed solution to the problem and others like it in your codebase.

Of course, it's possible that this isn't dynamic enough for you, and that you already know Class::Accessor like the back of your hand and the CTO insists that the API is frozen and so on. But if not, I'd really recommend you use Class::Accessor (or Class::Accessor::Fast or Class::Accessor::Faster). I bet you could make a factory on top of that if you really need one.

Anyhow, here's a simple example of that module in action:

package Foo; use strict; use warnings; use base qw(Class::Accessor); __PACKAGE__->mk_accessors(qw(spiro london)); 1;

Meanwhile, in a nearby t/*.t:

my $foo = Foo->new( { spiro => 'Agnew', london => 'England' } ); isa_ok( $foo, 'Foo' ); is( $foo->spiro, 'Agnew', "spiro" ); is( $foo->london, 'England', "london" ); ok( $foo->spiro('Not really Agnew'), "set spiro" ); ok( $foo->london('Ontario'), "set london" ); is( $foo->spiro, 'Not really Agnew', "spiro" ); is( $foo->london, 'Ontario', "london" );

In reply to Re: a simple matter of elegance by frostman
in thread a simple matter of elegance by spiros

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.