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

tcl like 1 loop with two operators

by ISAI student (Scribe)
on Jan 24, 2011 at 12:46 UTC ( #883927=perlquestion: print w/ replies, xml ) Need Help??
ISAI student has asked for the wisdom of the Perl Monks concerning the following question:

Hello all. I have been using Tcl as an EE, and using PERL. Tcl has a way of looping with two iteration variables: It looks something like this:
foreach i {1 2} j {3 4} { puts $i puts $j }
The machine would output:
1 3 2 4
W/o a need for an integer iterator. The language engine checks for list/array length. Is there something similar in PERL?

Comment on tcl like 1 loop with two operators
Select or Download Code
Re: tcl like 1 loop with two operators
by Corion (Pope) on Jan 24, 2011 at 12:58 UTC

    I'd use List::MoreUtils::natatime ("n at a time"):

    my $it = natatime 3, 1,2,3,4; while (my $i, $j = $it->()) { ... };

    ... or, if you have the data in two lists already, List::MoreUtils::pairwise (or ::each_arrayref, but have a look List::MoreUtils yourself)

    pairwise { print $a; print $b; } @a, @b

      E.g., with List::MoreUtils::each_array():

      >perl -wMstrict -le "use List::MoreUtils qw(each_array); my @ra = qw(a b c); my $pair_iter = each_array @ra, @{[ qw(x y z) ]}; while (my ($i, $j) = $pair_iter->()) { print qq{$i, $j}; } " a, x b, y c, z
Re: tcl like 1 loop with two operators
by JavaFan (Canon) on Jan 24, 2011 at 13:26 UTC
    Not natively. I would write that as:
    foreach my $fred ([1, 3], [2, 4]) { my($i, $j) = @$fred; say $i; say $j; }
      Or in case if arrays with $i and $j values are predefined, I would write it like that:
      my @i=(1,2); my @j=(3,4); my @a = map {[$i[$_],$j[$_]]} 0..$#i; foreach my $ij (@a){ my ($i, $j) = @{$ij}; say $i; say $j; }
      OR if it's necessary to emulate TCL behaviour for different lengths of arrays with $i and $j values, I would write it like that:
      my @i=(1,2); my @j=(3,4,5); my @len = sort(scalar(@i),scalar(@j)); my @a = map {[$i[$_],$j[$_]]} 0..$len[-1]; foreach my $ij (@a){ my ($i, $j) = @{$ij}; print $i."\n"; print $j."\n"; }
Re: tcl like 1 loop with two operators
by Fletch (Chancellor) on Jan 24, 2011 at 13:31 UTC

    Algorithm::Loops might also be of interest.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://883927]
Front-paged by Anonyrnous Monk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2015-07-05 21:43 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 (68 votes), past polls