Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: Arbitrarily Nested HoH

by Limbic~Region (Chancellor)
on Oct 15, 2010 at 21:26 UTC ( [id://865572]=note: print w/replies, xml ) Need Help??


in reply to Re: Arbitrarily Nested HoH
in thread Arbitrarily Nested HoH

apomatix,
I wonder how else you thought of doing it.

As I indicated, I considered an iterator. Here is a very unpolished working version:

my $next = hash_walker(\%data); while (my @row = $next->()) { print join(',', @row), "\n"; } sub hash_walker { my ($href) = @_; die "Not a hash ref" if ref($href) ne 'HASH'; my (@ref, @key) = ($href, ()); while (ref($href) eq 'HASH') { my ($key, $val) = each %$href; push @key, $key; push @ref, $val; $href = $val; } my ($val, $done) = (pop @ref, undef); return sub { return () if $done; my @row = (@key, $val); my ($k, $v) = each %{$ref[-1]}; if (defined $k) { ($key[-1], $val) = ($k, $v); return @row; } my $idx = $#ref; while ($idx--) { my ($k, $v) = each %{$ref[$idx]}; next if ! defined $k; $key[$idx] = $k; $ref[$idx + 1] = $v; for ($idx + 1 .. $#ref) { my ($k, $v) = each %{$ref[$_]}; $key[$_] = $k; $ref[$_ + 1] = $v; } $val = pop @ref; return @row; } $done = 1; return @row; }; }

As you can see, it is far more complex than the recursive solution. Also, the iterator could result in bizarre behavior if the hash isn't walked all at once. This is because each itself is an iterator that is reset any time there is a call to keys or values. In the recursive version, the hash is traversed all at once so there isn't an opportunity to reset the iterator mid-traversal.

Here is the stack based iterative version I was thinking of. I think it is the nicest because it is how my brain works:

output_hash(\%data); sub output_hash { my ($href) = @_; die "Not a hashref" if ref($href) ne 'HASH'; my (@work, @row) = ($href, ()); while (@work) { my $item = pop @work; my ($k, $v) = each %$item; next if ! defined $k; if (ref($v) eq 'HASH') { push @work, $item, $v; $row[$#work - 1] = $k; next; } push @work, $item; print join(',', @row, $k, $v), "\n"; } }

However, I don't think your solution would be easy for someone "just learning Perl".

Why? That's an honest question. Provided you understand references (which he does), it should be straight forward. That is unless you are like me and have a hard time thinking recursively but the whole point of writing it recursively was that most programmers I know think that way naturally. What about it do you think a seasoned C++ programmer would find hard to understand?

Cheers - L~R

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-03-28 20:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found