Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:
for my $let (keys %hash) { for my $num (keys %{$hash{$let}}) { for my $name (keys %{$hash{$let}{$num}}) { print join(',', $let, $num, $name, $hash{$let}{$num}{$name +}), "\n"; } } }
The trouble was, the data structure was going to be an arbitrary number of levels deep. My first inclination was to reach for Algorithm::Loops but it didn't seem like a good fit. My second idea was to write an iterator (see Arbitrarily Nested Loops) but I wanted a coworker who is just learning perl (former C++ developer) to be able to maintain it. In a few minutes, I came up with a recursive solution which surprised me.
On my way home, I thought of several other ways of doing it and I was wondering how others might solve the problem. That is my question - how would you do it? I have provided my recursive solution below to get the ball rolling.
output_hash(\%data, []); sub output_hash { my ($href, $item) = @_; die "Not a hashref" if ref($href) ne 'HASH'; my ($key, $val) = each %$href; if (ref($val) ne 'HASH') { for my $key (sort keys %$href) { print join(',', @$item, $key, $href->{$key}), "\n"; } return; } for my $key (sort keys %$href) { push @$item, $key; output_hash($href->{$key}, $item); pop @$item; } }
Cheers - L~R
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Arbitrarily Nested HoH
by BrowserUk (Patriarch) on Oct 15, 2010 at 04:44 UTC | |
|
Re: Arbitrarily Nested HoH
by bduggan (Pilgrim) on Oct 15, 2010 at 03:40 UTC | |
|
Re: Arbitrarily Nested HoH
by muba (Priest) on Oct 15, 2010 at 01:58 UTC | |
|
Re: Arbitrarily Nested HoH
by ig (Vicar) on Oct 15, 2010 at 04:30 UTC | |
|
Re: Arbitrarily Nested HoH
by llancet (Friar) on Oct 15, 2010 at 05:53 UTC | |
|
Re: Arbitrarily Nested HoH
by juster (Friar) on Oct 15, 2010 at 07:35 UTC | |
|
Re: Arbitrarily Nested HoH
by apomatix (Novice) on Oct 15, 2010 at 02:31 UTC | |
by Limbic~Region (Chancellor) on Oct 15, 2010 at 21:26 UTC | |
|
Re: Arbitrarily Nested HoH
by locked_user sundialsvc4 (Abbot) on Oct 15, 2010 at 13:32 UTC | |
by MidLifeXis (Monsignor) on Oct 15, 2010 at 14:58 UTC | |
by locked_user sundialsvc4 (Abbot) on Oct 15, 2010 at 17:08 UTC |