Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Modifying Reference Array via Push in Subroutine

I have an array I want to modify in a subroutine. It gets passed in by reference as the second argument. It doesn't seem to get modified, since when I return, the length of the array is the same as the original value.

Here's a snippet of what I did:

sub readLine
{
    my @array = @{$_[1]};
    #Push value onto array
    push @array, $myvalue;
}

sub main 
{
    my @array = ();
    #Pass by reference
    readLine($argument1, \@array);

    print @array; #Prints 0
}

I'm new to Perl so please let me know if I'm doing this correctly. I read answers to similar questions and it's still not printing the correct value (1) for me. I have the latest version of Perl installed.


1 Answers

The original array isn't getting modified because you're making a copy of it into @array in readLine(). You need to do something like this instead, where you're acting upon the actual reference instead of just a copy:

use strict;
use warnings;
use Data::Dump;

main();

sub main {
    my @array;
    foo(\@array, 'bar', 'bat', 'baz');
    dd(@array);
}

sub foo {
    my ($aref, @args) = @_;
    push(@$aref, @args);
}

Output:

("bar", "bat", "baz")
like image 104
Matt Jacob Avatar answered Jun 02 '26 21:06

Matt Jacob