下面的代码.
sub max
{
if (@_[0] > @_[1])
{
@_[0];
}
else
{
@_[1];
}
}
print "biggest is ".&max(37,25);
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到以下警告,
Scalar values @_[0] better written as $_[0] at file.pl line 3.
Scalar values @_[1] better written as $_[1] at file.pl line 3.
Scalar values @_[0] better written as $_[0] at file.pl line 5.
Scalar values @_[0] better written as $_[0] at file.pl line 9.
biggest is 37.
Run Code Online (Sandbox Code Playgroud)
虽然我得到了正确的输出,但我想知道这个警告背后的原因是什么,因为我认为@_在子程序中使用是合适的$_.
TLP*_*TLP 25
问题是您通过使用数组切片而不是标量来引用单个数组元素.就像错误说的那样.数组切片是数组中元素的列表,例如:
my @a = (0 .. 9);
print @a[0,3,4]; # prints 034
Run Code Online (Sandbox Code Playgroud)
相反,当您引用单个数组元素时,您使用标量前缀$:
print $a[3]; # prints 3
Run Code Online (Sandbox Code Playgroud)
所以,当你这样做
@_[0];
Run Code Online (Sandbox Code Playgroud)
Perl告诉你,引用标量值的正确方法是不使用数组切片,而是使用标量符号:
$_[0];
Run Code Online (Sandbox Code Playgroud)
就这些.
尝试通过这个例子来理解它:
@array = (1,2,3); #array is the name of the array and @ means that it's an array
print $array[1];
#this will print element at index 1 and you're doing it in scalar context
Run Code Online (Sandbox Code Playgroud)
相似地,
@_ = (1,2,3); #_ is the name of the array
print $_[1];
#this will print element at index 1 of array _ and again you're doing it in scalar context
Run Code Online (Sandbox Code Playgroud)