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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With