Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Arbitrarily Nested HoH

by juster (Friar)
on Oct 15, 2010 at 07:35 UTC ( [id://865422]=note: print w/replies, xml ) Need Help??


in reply to Arbitrarily Nested HoH

Another solution using map. Does not pass an extra state variable around. More like a DFS approach. Handles array refs too. Uses brackets and curly brackets to differentiate between arrays and hashes.
sub flatten { my ($value) = @_; my $rtype = ref $value or return "=$value\n"; # ends recursion if ( $rtype eq 'ARRAY' ) { return map { my $i = $_; map { "[$i]$_" } flatten( $value->[ $_ ] ); } ( 0 .. $#$value ); } elsif ( $rtype eq 'HASH' ) { return map { my $k = $_; map { "{$k}$_" } flatten( $value->{ $_ } ); } sort keys %$value; } die 'flatten only handles scalars, arefs, or hrefs'; } print for flatten( \%hohoh );

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://865422]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-24 04:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found