Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Perl中访问函数参数? 在C++中,我会做这样的事情:< /P> void一些函数(const char*str,…); 一些功能(“hi%SUR%d”、“n00b”、420);_Perl_Subroutine - Fatal编程技术网

如何在Perl中访问函数参数? 在C++中,我会做这样的事情:< /P> void一些函数(const char*str,…); 一些功能(“hi%SUR%d”、“n00b”、420);

如何在Perl中访问函数参数? 在C++中,我会做这样的事情:< /P> void一些函数(const char*str,…); 一些功能(“hi%SUR%d”、“n00b”、420);,perl,subroutine,Perl,Subroutine,在PHP中,我希望这样做: 函数some_func() { $args=func_get_args(); } 一些(神圣的,$moly,$guacomole); 如何在Perl中实现这一点 sub-wut{ #这里有什么? } 您可以执行以下操作: sub wut { my @args = @_; ... } 调用函数时,Perl会自动填充特殊的@变量。您可以通过多种方式访问它: 直接使用@或其中的单个元素作为$[0],$[1],等等 通过将其分配给另一个数组,如上所示 通过将其分

在PHP中,我希望这样做:

函数some_func() { $args=func_get_args(); } 一些(神圣的,$moly,$guacomole); 如何在Perl中实现这一点

sub-wut{
#这里有什么?
}
您可以执行以下操作:

sub wut {
  my @args = @_;
  ...
}
调用函数时,Perl会自动填充特殊的
@
变量。您可以通过多种方式访问它:

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

    您还可以使用
    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";
      ...
    }
    

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

    如果有很多参数,您可能希望避免复制它们:
    sub wut{for my$arg(@){blah blah blah}
    。不过,请注意这一点,因为
    @
    中的每个元素都是原始参数的别名,您可以更改调用变量。您还可以通过
    my%args=@
    
    wut($arg1, { option1 => 'hello', option2 => 'goodbye' });
    
    sub wut {
      my $arg1 = shift;
      my $opts = shift;
      my $option1 = $opts->{option1} || "default";
      my $option2 = $opts->{option2} || "default2";
      ...
    }