My question in Perl is:
Define 2×2 arrays using anonymous lists. Pass the arrays to a subroutine and add them together. Return a reference to sum array and print the values from the main part of the program.
My script is:
#!/usr/bin/perl
use strict;
use warnings;
my @array = ([1,2],[4,5]);
my $refarray = \@array;
print sumarray($refarray);
sub sumarray
{
$refarray = shift;
foreach (@{$refarray})
{
$refarray = ($refarray[0]->[0]+$refarray[1]->[0],$refarray[0]->[1]+$refarray[1]->[1]);
}
return $refarray;
}
Where am I going wrong? Please help. Thanks in advance.
I am getting the output as 0.
If I use use strict; and use warnings; I will get the error message as
Global symbol "@refarray" requires explicit package name at line 23.
Global symbol "@refarray" requires explicit package name at line 23.
Global symbol "@refarray" requires explicit package name at line 23.
Global symbol "@refarray" requires explicit package name at line 23.
Execution aborted due to compilation errors.
Few problems with your code: –
$refarraywhich you should not do.$refarray[0]->[0]will not compile. Since$refarrayis a reference to an array, you should either use its 1st element using arrow: –$refarray->[0][0], or you need to de-reference it before using the way you are using: –$$refarray[0]->[0].Having said that, I think you should replace your
subroutinewith this one: –OUTPUT: –