简体   繁体   English

如何将Perl数组引用中的元素作为子例程的单独参数传递?

[英]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]) ? 如何在不写foo情况下调用foo foo($$args[0], $$args[1], $$args[2])

You dereference an array reference by sticking @ in front of it. 您可以通过在其前面粘贴@来取消引用数组引用。

foo( @$args );

Or if you want to be more explicit: 或者如果你想更明确:

foo( @{ $args } );

This should do it: 这应该这样做:

foo(@$args)

That is not actually an apply function. 这实际上不是一个apply函数。 That syntax just dereferences an array reference back to plain array. 该语法只是将数组引用取消引用回到plain数组。 man perlref tells you more about referecences. man perlref告诉你更多关于referecences

尝试这个:

foo(@$args);
foo(@$args);

Or, if you have a reference to foo : 或者,如果你有foo的引用:

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

It's simple. 这很简单。 foo(@{$args}) FOO(@ {$ ARGS})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM