Given a hash reference I want to access values from, I am tired of writing
say $h->{foo}, $h->{bar}, $h->{doz};
but I want
say $h->foo, $h->bar, $h->doz;
What is the easiest way to do so, without creating a copy of the hash? I managed it with a single line:
sub GET::AUTOLOAD { $GET::AUTOLOAD =~ /::(\w+)$/; $_[0]->{ $1 }; }
my $h = { foo => 1, bar => 2, doz => 3 };
bless $h, 'GET';
say $h->foo, $h->bar, $h->doz;
But I'd prefer a solution that works with nested JSON-like structures (blessing all nested hashrefs, not blessing array references but hashrefs in arrayrefs etc.), to do:
my $h = { foo => 1, bar => [ 2, { doz => 3 } ] };
getter($h);
say $h->foo->[1]->doz; # 3
Is there a CPAN module that provides such a simple
getter method?
P.S: One could write it, but I prefer to use a module:
use Scalar::Util qw();
sub GET::AUTOLOAD { $GET::AUTOLOAD =~ /::(\w+)$/; $_[0]->{ $1 }; }
sub getter {
my $h = $_[0];
my $r = Scalar::Util::reftype($h) or return;
if ($r eq 'ARRAY') {
getter($_) for @$h;
} elsif ($r eq 'HASH') {
bless $h, 'GET';
getter($h->{$_}) for keys %$h;
}
$h;
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.