Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass the elements in a Perl array reference as separate arguments to a subroutine?

I have a list that contains arguments I want to pass to a function. How do I call that function?

For example, imagine I had this function:

sub foo {
  my ($arg0, $arg1, $arg2) = @_;
  print "$arg0 $arg1 $arg2\n";
}

And let's say I have:

my $args = [ "la", "di", "da" ];

How do I call foo without writing foo($$args[0], $$args[1], $$args[2])?

like image 713
Frank Krueger Avatar asked Jan 18 '10 18:01

Frank Krueger


People also ask

How do you pass arguments to a subroutine in Perl?

Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

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

By using the backslash operator on a variable, subroutine, or value.


2 Answers

You dereference an array reference by sticking @ in front of it.

foo( @$args );

Or if you want to be more explicit:

foo( @{ $args } );
like image 72
friedo Avatar answered Oct 21 '22 05:10

friedo


This should do it:

foo(@$args)

That is not actually an apply function. That syntax just dereferences an array reference back to plain array. man perlref tells you more about referecences.

like image 22
Juha Syrjälä Avatar answered Oct 21 '22 05:10

Juha Syrjälä