Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Inspiration whacked me in the head yesterday, and I realized that it was pretty easy to take an arbitrary hash reference and turn it into an object, so that instead of writing $hash->{key} I can just write $hash->key, saving two characters and giving me protection from typos. Enter Util::H2O:

use Util::H2O; my $hash = h2o { foo => "bar", x => "y" }, qw/ more keys /; print $hash->foo, "\n"; # prints "bar" $hash->x("z"); # setter

Deeply nested structures can be converted too...

my $struct = { hello => { perl => { world => "yay" } } }; h2o -recurse, $struct; print $struct->hello->perl->world, "\n"; # prints "yay"

The function blesses its hashref argument into a new package, and returns that hashref as well. The hashrefs otherwise remain the same as before, so you can still use $hash->{key} and so on if you like. The newly created package is cleaned up by default when the object is destroyed (configurable). These objects are of course a bit less performant than a regular hashref, but this wasn't intended for high-performance applications.

Update: As of the freshly-released v0.06, the h2o function also locks the hash's keyset by default, to prevent typos when using the hash like a regular hashref. This can be disabled with the -lock=>0 option. /Update

I quickly realized I could do more with this, like add methods to these objects:

my $obj = h2o -meth, { one => 123, two => 456, sum => sub { my $self = shift; return $self->one + $self->two; } }; print $obj->sum, "\n"; # prints "579"

And I could even make it easy to create classes; the -new option generates a constructor:

h2o -class=>'Point', -new, -meth, { angle => sub { my $self = shift; atan2($self->y, $self->x) }, }, qw/ x y /; my $one = Point->new(x=>1, y=>2); my $two = Point->new(x=>3, y=>4); $two->y(5); printf "%.4f\n", $two->angle; # prints 1.0304

Yes, I realize that might be taking it a little bit too far, but it was easy to implement - plus, I figured this could possibly be useful for whipping up mock objects in tests. And yes, I'm aware similar tools exist ;-)


In reply to Converting Hashes to Objects by haukex

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

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

    How do I use this? | Other CB clients
    Other Users?
    Others browsing the Monastery: (5)
    As of 2020-09-25 07:06 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      If at first I dont succeed, I










      Results (136 votes). Check out past polls.

      Notices?