voj has asked for the wisdom of the Perl Monks concerning the following question:
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: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;
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:my $h = { foo => 1, bar => [ 2, { doz => 3 } ] }; getter($h); say $h->foo->[1]->doz; # 3
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Create Read-Accessors for a given hash
by Corion (Patriarch) on Feb 28, 2013 at 09:05 UTC | |
|
Re: Create Read-Accessors for a given hash
by tobyink (Canon) on Feb 28, 2013 at 09:05 UTC |