Domanda

I am passing an array as ref to a sub. There I have to add values to it, but its not working. my code is:

my @scalarArray1 = ();

sub CompareScalers() {
    fillScalarArray( $_[0], \@scalarArray1 );    #pass arrays by ref
}

sub fillScalarArray() {
    my $filename = $_[0];                        #first file name as input file
    open( my $fh, '<:encoding(UTF-8)', $filename ) or die "Could not open file '$filename' $!";
    my @array = @{ $_[1] };
    while ( my $row = <$fh> ) {
        push( @array, $row );
    }
}

The debug print at end of while loop for the size of arrays is as follows:

 DB<29> p $#scalarArray1
-1
 DB<30> p $#array
1551
È stato utile?

Soluzione

my @array = @{$_[1]} makes a copy of the array. When you push items onto the copy, the original array is not affected.

I assume you want your function to actually modify the array pointed to by the reference. To do that, eliminate the my @array = ... line and change your push calls to be like the following, which uses the reference without copying:

push (@{$_[1]} , $row);

For readability, you can assign the array reference to a named scalar variable and use that instead:

my $arrayRef = $_[1];
push @{$arrayRef}, $row;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top