Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over multiple lists at the same time in Perl?

Tags:

arrays

list

perl

I need to create a text file (aptest.s) that Ican use to read into another program. I am using Perl because I have a large list to work from. My code is as follows (which does not give the desired output - shown after code and actual output). Any help would be appreciated.

#!/usr/bin/perl -w
chdir("D://projects//SW Model ODME");
@link = ("319-116264||319-118664","320-116380||320-116846","321-119118||321-119119","322-115298||322-119087");
@link1 = ("116264-319||118664-319","116380-320||116846-320","119118-321||119119-321","115298-322||119087-322");
open (FSAS, ">>aptest.s");
foreach $link (@link) {
    foreach $link1 (@link1){
    print FSAS "other code \n";
    print FSAS "PATHLOAD SELECTLINK=(Link=".$link."), VOL[2]=MW[1] \n";
    print FSAS "PATHLOAD SELECTLINK=(Link=".$link1."), VOL[3]=MW[2] \n";
    print FSAS "other code \n";
}
}

Actual Output :

other output
PATHLOAD SELECTLINK=(Link=319-116264||319-118664), VOL[2]=MW[1] 
PATHLOAD SELECTLINK=(Link=116264-319||118664-319), VOL[3]=MW[2] 
other output 

other output
PATHLOAD SELECTLINK=(Link=**319-116264||319-118664**), VOL[2]=MW[1] 
PATHLOAD SELECTLINK=(Link=**116380-320||116846-320**),      VOL[3]=MW[2] 
other output

Desired Output

other output
PATHLOAD SELECTLINK=(Link=319-116264||319-118664), VOL[2]=MW[1] 
PATHLOAD SELECTLINK=(Link=116264-319||118664-319), VOL[3]=MW[2] 
other output

other output
PATHLOAD SELECTLINK=(Link=**320-116380||320-116846**), VOL[2]=MW[1] 
PATHLOAD SELECTLINK=(Link=**116380-320||116846-320**), VOL[3]=MW[2] 
other output
like image 336
Krishnan Avatar asked May 04 '09 23:05

Krishnan


People also ask

Can I iterate over a Set?

There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...

What is foreach loop in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.


1 Answers

See each_array in List::MoreUtils:

#!/usr/bin/perl

use strict;
use warnings;

use List::MoreUtils qw( each_array );

my @x = qw( A B C D E F );
my @y = (10, 11, 12, 13, 14, 15);

my $it = each_array( @x, @y );
while ( my ($x, $y) = $it->() ) {
    print "$x = $y\n";
}
__END__
like image 193
Sinan Ünür Avatar answered Oct 13 '22 08:10

Sinan Ünür