Search code examples
perlargumentsperl-module

expand array to arguments list in perl


I have something like the following code

my @array = ["hello","hi","fish"];
sub this_sub {
  my $first = $_[0];
  my $second = $_[1];
  my $third = $_[2];
}
this_sub(@array);

How can I make the array expand into an argument list so that first, second and third will get the value from the strings in the array. like below.

  • first = "hello"
  • second = "hi"
  • third = "fish"

Solution

  • Your code is wrong. To assign a list to an array, enclose it in normal parentheses:

    my @array = ("hello", "hi", "fish");
    

    Square brackets define an anonymous array, i.e. a referenco to a list, which is a scalar:

    my $array_ref = ["hello", "hi", "fish"];
    

    If you want to send a reference, you have to dereference it in the sub:

    sub this_sub {
        my ($first, $second, $third) = @{ $_[0] };
    }