I am having trouble passing and reading arguments inside subroutine which is expected to have two arrays.
sub two_array_sum { # two_array_sum ( (1 2 3 4), (2, 4, 0, 1) ) -> (3, 6, 3, 5)
# I would like to use parameters @a and @b as simply as possible
}
# I would like to call two_array_sum here and pass two arrays, @c and @d
I have seen and tried several examples from the web, but none of them worked for me.
You can't pass arrays to functions. Functions can only accept a lists of scalars for argument. As such, you need to pass scalars that provide sufficient data to recreate the arrays. The simplest means of doing so is passing references to the arrays.
Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function. Example 1: Here a single list is passed to the subroutine and their elements are displayed.
You can't pass arrays to functions. Functions can only accept a lists of scalars for argument. As such, you need to pass scalars that provide sufficient data to recreate the arrays.
The simplest means of doing so is passing references to the arrays.
sub two_array_sum {
my ($array0, $array1) = @_;
my @array0 = @$array0;
my @array1 = @$array1;
return map { $array0[$_] + $array1[$_] } 0..$#array0;
}
You can even avoid reconstructing the arrays and work with the references directly.
sub two_array_sum {
my ($array0, $array1) = @_;
return map { $array0->[$_] + $array1->[$_] } 0..$#$array0;
}
Usage:
my @array0 = (1, 2, 3, 4);
my @array1 = (2, 4, 0, 1);
two_array_sum(\@array0, \@array1);
Square brackets construct an anonymous array (populated with the result of the expression within) and returns a reference to that array. Therefore, the above could also be written as follows:
two_array_sum([1, 2, 3, 4], [2, 4, 0, 1]);
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