Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing two or more arrays to a Perl subroutine

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.

like image 991
eold Avatar asked Apr 15 '11 17:04

eold


People also ask

How do I pass multiple arrays to a subroutine in Perl?

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.

How do I pass a subroutine list in Perl?

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.


1 Answers

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]);
like image 76
ikegami Avatar answered Sep 25 '22 15:09

ikegami