'@_' 在 Perl 中有什么作用? [英] What does '@_' do in Perl?

查看:42
本文介绍了'@_' 在 Perl 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览我在 Perl 类中编写的一些代码,我注意到了这一点.

I was glancing through some code I had written in my Perl class and I noticed this.

my ($string) = @_;
my @stringarray = split(//, $string);

我想知道两件事:变量在括号中的第一行,这是您在声明多个变量时所做的事情,如果我删除它们,它仍然可以正常工作吗?

I am wondering two things: The first line where the variable is in parenthesis, this is something you do when declaring more than one variable and if I removed them it would still work right?

第二个问题是@_ 有什么作用?

The second question would be what does the @_ do?

推荐答案

@_ 变量是一个数组,其中包含传递给子程序的所有参数.

The @_ variable is an array that contains all the parameters passed into a subroutine.

$string 变量周围的括号是绝对必要的.它们表示您正在从数组中分配变量.没有它们,@_ 数组在标量上下文中被分配给 $string,这意味着 $string 将等于传递给子程序的参数.例如:

The parentheses around the $string variable are absolutely necessary. They designate that you are assigning variables from an array. Without them, the @_ array is assigned to $string in a scalar context, which means that $string would be equal to the number of parameters passed into the subroutine. For example:

sub foo {
  my $bar = @_;
  print $bar;
}

foo('bar');

这里的输出是 1——在这种情况下绝对不是你所期望的.

The output here is 1--definitely not what you are expecting in this case.

或者,您可以不使用 @_ 数组而是使用 shift 函数来分配 $string 变量:

Alternatively, you could assign the $string variable without using the @_ array and using the shift function instead:

sub foo {
  my $bar = shift;
  print $bar;
}

使用一种方法而不是另一种方法是一种品味问题.我问了这个问题 如果您有兴趣,可以查看.

Using one method over the other is quite a matter of taste. I asked this very question which you can check out if you are interested.

这篇关于'@_' 在 Perl 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆