Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^5: Using an array element as a loop iterator

by AnomalousMonk (Archbishop)
on Nov 08, 2013 at 16:27 UTC ( [id://1061730]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Using an array element as a loop iterator
in thread Using an array element as a loop iterator

It sounds as if you might want something like Algorithm::Loops::NestedLoops (among many similar on CPAN):

>perl -wMstrict -le "my $number = 99; my $letter = 'Z'; my $word = 'zot'; ;; my @words= qw(foo bar); ;; for my $number (1 .. 3) { for my $letter (qw(A B C)) { for my $word (@words) { do_something_with($number, $letter, $word); } } } ;; print qq{post-loop: '$number' '$letter' '$word' \n} ;; sub do_something_with { my (@args) = @_; ;; print qq{@args}; } ;; ;; use Algorithm::Loops qw(NestedLoops); ;; print qq{using NestedLoops:}; NestedLoops [ [ 1 .. 3 ], [ qw(A B C) ], \@words, ], \&do_something_with ; " 1 A foo 1 A bar 1 B foo 1 B bar 1 C foo 1 C bar 2 A foo 2 A bar 2 B foo 2 B bar 2 C foo 2 C bar 3 A foo 3 A bar 3 B foo 3 B bar 3 C foo 3 C bar post-loop: '99' 'Z' 'zot' using NestedLoops: 1 A foo 1 A bar 1 B foo 1 B bar 1 C foo 1 C bar 2 A foo 2 A bar 2 B foo 2 B bar 2 C foo 2 C bar 3 A foo 3 A bar 3 B foo 3 B bar 3 C foo 3 C bar

With this approach it's easy to add arrays to arbitrary depth, albeit with attendant exponential explosion!

Update: Changed example code to show  \@words taking reference to array.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-25 06:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found