Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Dynamically create a foreach loop within a foreach loop?

by educated_foo (Vicar)
on Dec 11, 2013 at 15:28 UTC ( #1066635=note: print w/ replies, xml ) Need Help??


in reply to Dynamically create a foreach loop within a foreach loop?

As mentioned elsewhere, you can use recursion:

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


Comment on Re: Dynamically create a foreach loop within a foreach loop?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (13)
As of 2015-07-06 12:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (74 votes), past polls