0

I have this perl script:

my %perMpPerMercHash;

foreach my $sheet () {   #proper ranges specified
    foreach my $row ( ) {    #proper ranges specified
        #required variables declared.
        push(@{$perMpPerMercHash{join("-", $mercId, $mpId)}}, $mSku); 
    }
}

#Finally 'perMpPerMercHash' will be a hash of array`
foreach my $perMpPerMerc ( keys %perMpPerMercHash ) {
    &genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
}

sub genFile {
    my ( $outFileName, @skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, @skuArr ) = @_;
    my $count = 1;
    print Dumper \@skuArr;    #Printing correctly, 8-10 values.
    foreach my $sku ( @skuArr ) {   #not iterating.
        print "loop run" , $sku, "\n";   #printed only once.
    }
}

Can somebody please help why this is happening. I am new to perl and could not understand this anomaly.

EDIT: output of Dumper:

$VAR1 = [
          'A',
          'B',
          'C',
        ];
4

1 回答 1

3

当你这样做

&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});

您正在传递对数组的引用。

所以在

sub genFile {
    my ( $outFileName, @skuArr ) = @_;

你所要做的 :

sub genFile {
    my ( $outFileName, $skuArr ) = @_;

然后使用@$skuArr.

看看参考资料

修改后的 genFile sub 将是:

sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    my $output = new IO::File(">$outFileName");
    my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
 #mpId is generated.
    &prepareMessage($writer, $mpId, @$skuArr);
}

另一个子不需要修改。

或者您可以始终skuArr 通过引用传递:

&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
...
sub genFile {
    my ( $outFileName, $skuArr ) = @_;
    ...
    &prepareMessage($writer, $mpId, $skuArr);
}

sub prepareMessage {
    my ( $writer,  $mpId, $skuArr ) = @_;
    my $count = 1;
    print Dumper $skuArr; 
    foreach my $sku ( @$skuArr ) {
        print "loop run" , $sku, "\n";
    }
}
于 2013-10-30T13:06:35.660 回答