17

在 C++ 中,我会做这样的事情:

void some_func(const char *str, ...);
some_func("hi %s u r %d", "n00b", 420);

在 PHP 中,我会这样做:

function some_func()
{
    $args = func_get_args();
}
some_func($holy, $moly, $guacomole);

我如何在 Perl 中做到这一点?

sub wut {
    # What goes here?
}
4

1 回答 1

32

你会这样做:

sub wut {
  my @args = @_;
  ...
}

@_当您调用函数时,Perl 会自动填充特殊变量。您可以通过多种方式访问​​它:

  • 直接地,通过简单地使用@_或其中的单个元素作为$_[0], $_[1], 等等
  • 通过将其分配给另一个数组,如上所示
  • 通过将其分配给标量列表(或可能是哈希,或另一个数组,或它们的组合):

    子 wut {
      我的 ($arg1, $arg2, $arg3, @others) = @_;
      ...
    }

请注意,在这种形式中,您需要将数组@others放在末尾,因为如果您之前将其放入,它将吞噬@_. 换句话说,这是行不通的:

sub wut {
  my ( $arg1, @others, $arg2 ) = @_;
  ...
}

您还可以使用shift以下方法提取值@_

sub wut {
  my $arg1 = shift;
  my $arg2 = shift;
  my @others = @_;
  ...
}

请注意,如果您不提供参数,shift它将自动运行。@_

编辑:您还可以通过使用散列或散列引用来使用命名参数。例如,如果您wut()这样调用:

wut($arg1, { option1 => 'hello', option2 => 'goodbye' });

...然后您可以执行以下操作:

sub wut {
  my $arg1 = shift;
  my $opts = shift;
  my $option1 = $opts->{option1} || "default";
  my $option2 = $opts->{option2} || "default2";
  ...
}

这将是在函数中引入命名参数的好方法,这样您就可以稍后添加参数,而不必担心它们传递的顺序。

于 2011-04-19T16:00:03.580 回答