in reply to Dynamically create a foreach loop within a foreach loop?
As mentioned elsewhere, you can use recursion:
You can also use "eval" to build up the loops (hand-waving a bit):sub foo { my ($hash, @path) = @_; while (my ($k, $v) = each %$hash) { if (ref $v eq 'HASH') { foo($v, @path, $k); } else { # whatever } } }
In general, when you want nested loops and don't know how many beforehand, recursion is easiest.$depth = compute_hash_depth; $code = '...'; for (reverse 1..$depth) { my $prev = $_-1; $code = "while (my (\$k$_, \$v$_) = each \$v$prev) { $code }"; } eval $code;
|
---|
In Section
Seekers of Perl Wisdom