Sunil Sunil - 5 months ago 33
Perl Question

How to modify array elements using subroutine in perl

I am trying to modify the array passed to subroutine. I am passing the reference to the subroutine and assigning new values but it is not getting reflected in the caller side.
Below is my program.

sub receiveArray {
my $arrayref = @_;
@{$arrayref} = (4, 5, 6);
}

@ar = (1, 2,3 );
print "Values of the function before calling the function\n";
foreach my $var (@ar) {
print $var;
print "\n";
}
receiveArray(\@ar);
print "Values of the function after calling the function\n";
foreach my $var (@ar) {
print $var;
print "\n";
}


What is the problem in the above code. Any help would be greatly appreciated. Thanks in advance

Answer

You should start every Perl file you write with use strict; use warnings;. That will help you avoid errors like this.

The problem is in this line:

    my $arrayref = @_;

You're assigning an array to a scalar, so the array is evaluated in scalar context, which yields the number of elements in the array.

What you should do instead is:

    my ($arrayref) = @_;

Now it's using list assignment, putting the first function argument into $arrayref (and ignoring the rest, if any).

List assignment is documented in perldoc perldata (the part starting with "Lists may be assigned to ...").