Frank Krueger
Frank Krueger

Reputation: 70993

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])?

Upvotes: 6

Views: 277

Answers (5)

aartist
aartist

Reputation: 3236

It's simple. foo(@{$args})

Upvotes: 2

cjm
cjm

Reputation: 62109

foo(@$args);

Or, if you have a reference to foo:

my $func = \&foo;
...
$func->(@$args);

Upvotes: 4

friedo
friedo

Reputation: 66978

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

foo( @$args );

Or if you want to be more explicit:

foo( @{ $args } );

Upvotes: 11

Juha Syrjälä
Juha Syrjälä

Reputation: 34271

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.

Upvotes: 9

C. K. Young
C. K. Young

Reputation: 223043

Try this:

foo(@$args);

Upvotes: 6

Related Questions