Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
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 musing on the Monastery: (7)
As of 2015-07-29 06:11 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 (260 votes), past polls