Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: can we pass two variable to foreach loop

by ambrus (Abbot)
on Mar 28, 2007 at 18:26 UTC ( #607078=note: print w/ replies, xml ) Need Help??


in reply to can we pass two variable to foreach loop

What would you want it to do?

  1. Iterate on two arrays in paralel:
    @name = qw(fred wilma barney betty); @color = qw(black red blonde black); for $k (0 .. @name - 1) { print $name[$k] . " - " . $color[$k] . "\n" +} # fred - black # wilma - red # barney - blonde # betty - black
  2. Move a sliding window on an array:
    @name = qw(fred wilma barney betty); for $k (0 .. @name - 2) { print $name[$k] . " - " . $name[$k + 1] . "\ +n" } # fred - wilma # wilma - barney # barney - betty
  3. Take the elements of the array in twos:
    @name = qw(fred wilma barney betty); for $k (0 .. @name/2 - 1) { print $name[2 * $k] . " - " . $name[2 * $k + + 1] . "\n" } # fred - wilma # barney - betty
  4. Iterate on an array of pairs:
    @data = (["fred", "black"], ["wilma", "red"], ["barney", "blonde"], [" +betty", "black"]); @color = qw(black red blonde black); for $rec (@data) { my($name, $col +or) = @$rec; print $name . " - " . $color . "\n" } # fred - black # wilma - red # barney - blonde # betty - black
Or perhaps even something you would normally do with two levels of loops, like iterating on each combination of two names.


Comment on Re: can we pass two variable to 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://607078]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-07-25 21:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (175 votes), past polls