Как я могу выполнить итерации по нескольким спискам одновременно в Perl?

Вы импортируете test как present. Вместо использования test.testt() используйте present.testt(). Кроме того, ваш код страдает от проблемы circular import. Проблема кругового импорта

9
задан brian d foy 7 May 2009 в 05:00
поделиться

4 ответа

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__
21
ответ дан 4 December 2019 в 08:02
поделиться

Can you reduce the size of your code and example data while still reproducing the error? I can't immediately see the difference between the actual and expected output.

Sometimes, finding a minimal set of code and data that causes a problem will make the solution obvious.

Looking a bit more carefully, there's only one bit of output code that is variable:

print FSAS "PATHLOAD PATH=TIME, MW[1]=MI.1.1, SELECTLINK=(Link=".$link."), VOL[2]=MW[1] \n";
print FSAS "PATHLOAD PATH=TIME, MW[2]=MI.1.1, SELECTLINK=(Link=".$link1."), VOL[3]=MW[2] \n";

Your bug is likely to be there.

0
ответ дан 4 December 2019 в 08:02
поделиться

I think you're trying to create four separate blocks, with each element from the link array associated with the corresponding element from the link2 array?

However you're actually outputting sixteen blocks, one for each combination of link and link1.

Instead try:

foreach $i (0 .. $#link) {

   $link = $link[$i];
   $link1 = $link1[$i];

   ...
}
4
ответ дан 4 December 2019 в 08:02
поделиться

Читая ваш вопрос, было сложно сказать, что вы действительно хотели знать. Я считаю, что Синан Унур прав, и что вы хотите выполнять итерацию одновременно по двум массивам. По его словам, List :: MoreUtils предоставляет очень удобную функцию each_array () .

Также просто выполнить итерацию по одному или нескольким массивам по индексу.

Вы можете сгенерировать список индексов для использования с обычным циклом for. Здесь используется $ # для получения индекса последнего значения в массиве.

for ( 0..$#array ) { ... }

Или вы можете использовать цикл for в стиле C для генерации индексов. При этом используется тот факт, что массив, вычисленный в скалярном контексте, возвращает количество элементов.

for ( my $i=0; $i<@array; $i++ ) { ... }

Он также может быть записан с использованием $ # :

for ( my $i=0; $i<=$#array; $i++ ) { ... }

После прочтения вашего кода стало ясно, что вы не ' • знаком с операторами цитирования Perl . Их эффективное использование упрощает написание и чтение ваших скриптов.

В дружеском духе, позвольте мне привести ваш скрипт в порядок:

#!/usr/bin/perl

# Always:
use strict;
use warnings;

#my $TARGET_DIR  = 'D://projects//SW Model ODME';
my $TARGET_DIR  = '.';

my $TARGET_FILE = 'aptest.s';

# Using qw() makes long lists of 
# literals easier to type and read.
# Consider finding better names than link and link1.
# Something that describes the relationship between
# the two arrays.
my @link = qw(
    319-116264||319-118664
    320-116380||320-116846
    321-119118||321-119119
    322-115298||322-119087
);

my @link1 = qw(
    116264-319||118664-319
    116380-320||116846-320
    119118-321||119119-321
    115298-322||119087-322
);

# check the results of chdir.  
chdir($TARGET_DIR) 
    or die "Unable to enter $TARGET_DIR - $!\n";

# Use a lexical filehandle.
# Use 3 arg open
# Check the results of open - you need to know if it fails.
open (my $fsas, '>>', $TARGET_FILE)
    or die "Unable to open $TARGET_FILE - $!\n";

# Verify that the link arrays are both sized appropriately.
die "Link arrays are not the same size."
    unless @link == @link1;

# Loop over the indexes of the array.
# For very (very) large arrays it is 
# more efficient to use a C-style for loop:
#   for( my $i = 0; $i < @link; $i++ ) {
foreach my $i (0..$#link) {
    my $link  = $link[$i];
    my $link1 = $link1[$i];

    print $fsas Get_Link_Text($link, $link1);
}

# Broke out your formatting code into a routine for readability.
# Used a heredoc to make the formatting easier to read.
# Also, took advantage of variable interpolation in the heredoc to further
# improve readability.
# I preserved the whitespace at the end of lines, is it really necessary?
sub Get_Link_Text {
    my $link = shift;
    my $link1 = shift;

    return <<"--END_TEXT--"; 
RUN PGM=HWYLOAD 
MATI=daily_trucks.MAT  
NETI=FAF_Network_V11.net  
NETO=MiamiDade.NET 
PARAMETERS MAXITERS=1, GAP=0.001, COMBINE=EQUI  
FUNCTION {   
TC[1] = T0*(1+0.15*(V/100)^(4))}    
FUNCTION V = (VOL[1]) 
PHASE=ILOOP 
PATHLOAD PATH=TIME, MW[1]=MI.1.1, SELECTLINK=(Link=$link), VOL[2]=MW[1] 
PATHLOAD PATH=TIME, MW[2]=MI.1.1, SELECTLINK=(Link=$link1), VOL[3]=MW[2] 
ENDPHASE  
ENDRUN 


--END_TEXT--
}
2
ответ дан 4 December 2019 в 08:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: