6

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

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
  • 2
    Where does the `APPLY` come from? Is this a construct in another language? – daotoad Jan 18 '10 at 19:26
  • 3
    APPLY comes from LISP http://nostoc.stanford.edu/jeff/llisp/21.html – Juha Syrjälä Jan 18 '10 at 20:32
  • 1
    @daotoad Comes from Lisp but most languages have their equivalent form of it. It's one of those things that's really hard to Google for since various languages make up different terminology for the same thing. – Frank Krueger Jan 18 '10 at 22:11

5 Answers5

11

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

foo( @$args );

Or if you want to be more explicit:

foo( @{ $args } );
friedo
  • 65,762
  • 16
  • 114
  • 184
9

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.

Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
  • You might also consider not constructing the reference to begin with, i.e. `@args = ("la", "de", "dah")` or even `@args = qw(la de dah);` and then passing it with `foo(@args)`. This is cleaner and more straightforward than doing the reference dance, though if you have other constraints (the array is already part of a data structure, for instance) it's not a huge deal. –  Jan 19 '10 at 01:01
6

Try this:

foo(@$args);
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
4
foo(@$args);

Or, if you have a reference to foo:

my $func = \&foo;
...
$func->(@$args);
cjm
  • 61,471
  • 9
  • 126
  • 175
2

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

aartist
  • 3,145
  • 3
  • 33
  • 31