9

下面是代码。

sub max 
    {
        if (@_[0] > @_[1]) 
        {
            @_[0];
        }
        else
        {
            @_[1];
        }
    }
    print "biggest is ".&max(37,25);

当我运行它时,我收到以下警告,

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.

虽然我得到了正确的输出,但我想知道这个警告背后的原因是什么,因为我认为@_在子例程中使用比$_.

4

3 回答 3

25

问题是您通过使用数组切片而不是标量来引用单个数组元素。就像错误所说的那样。数组切片是数组中元素的列表,例如:

my @a = (0 .. 9);
print @a[0,3,4];    # prints 034

相反,当您引用单个数组元素时,您使用标量前缀$

print $a[3];        # prints 3

所以当你这样做时

@_[0];

Perl 告诉您引用量值的正确方法是不使用数组切片,而是使用标量表示法:

$_[0];

就这些。

于 2013-04-15T10:36:29.323 回答
3

试着用这个例子来理解它:

@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

相似地,

@_ = (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
于 2013-04-15T10:46:05.003 回答
1

您指的是数组,而不是标量。@_[0]意味着($_[0])。但是 perl 是这样的,clever所以它会警告您,您应该返回一个标量,而不是显式的单个元素列表。在这里你应该使用$_[0].

我建议使用原型,因为现在您可以调用max (1, 2, 3),结果将是2,而不是3. 所以定义为

sub max ($$) { $_[0] > $_[1]) ? $_[0] : $_[1] }

或者更好的是,您可以使用未定义数量 (>=2) 的元素。用 0 或 1 个项目来调用它可能毫无意义。

sub max (@) { 
    return undef if $#_<0; 
    my $s = shift; 
    for(@_) { $s = $_ if $_ > $s } $s 
} 
于 2013-04-15T10:57:58.810 回答