在Perl中分配多个数组子例程参数不起作用

Ant*_*GMO 1 perl

我对这个例子中的perl子例程参数感到困惑

当我在子程序参数中使用引用时,它可以工作:

@a = ( 1, 2 );
@b = ( 5, 8 );
@c = add_vecpair( \@a, \@b );
print "@c\n";
print $a[0];

sub add_vecpair {    # assumes both vectors the same length
    my ( $x, $y ) = @_;    # copy in the array references
    my @result;
    @$x[0] = 2;

    for ( my $i = 0; $i < @$x; $i++ ) {
        $result[$i] = $x->[$i] + $y->[$i];
    }

    return @result;
}
Run Code Online (Sandbox Code Playgroud)

但是当我不使用引用作为这样的参数时:

@a = ( 1, 2 );
@b = ( 5, 8 );
@c = add_vecpair( @a, @b );
print "@c\n";
print $a[0];

sub add_vecpair {    # assumes both vectors the same length
    my ( @x, @y ) = @_;    # copy in the array references
    my @result;
    print @y;
    for ( my $i = 0; $i < @x; $i++ ) {
        $result[$i] = $x[$i] + $y[$i];
    }

    return @result;
}
Run Code Online (Sandbox Code Playgroud)

..它不起作用.我什么时候需要使用引用作为子程序参数?

Jar*_*und 5

简短版:问题是这一行:

my (@x, @y) = @_; 
Run Code Online (Sandbox Code Playgroud)

作业贪婪.@x首先处理,并从@_它可以处理的多个值中给出.因为它可以处理所有这些,它最终得到所有的内容@_,并@y得到没有.

结果与此相同:

my @x = @_;   # Gets all of the arguements
my @y;        # Gets nothing, and is therefore declared but uninitialized.
Run Code Online (Sandbox Code Playgroud)

这就是为什么当子例程将多个值作为参数时,建议使用引用,并且这些值中的至少一个是数组或哈希值.


更长的版本: @_是传递给子例程的所有参数的组合,因此原始容器无关紧要.请考虑下面的代码段.第一个是你的,第二个是完全相同的东西,但更清楚地显示正在发生的事情.

@a = (1, 2);
@b = (5, 8);
add_vecpair(@a,@b);
Run Code Online (Sandbox Code Playgroud)

....是相同的:

add_vecpair(1, 2, 5, 8);
Run Code Online (Sandbox Code Playgroud)

为了进一步解决问题,如果以这种方式处理,哈希变得非常混乱:

%a = ('a' => 1, 
      'b' => 2);
%b = ('c' => 3,
      'd' => 4);
somefunction(%a, %b);
Run Code Online (Sandbox Code Playgroud)

...是相同的:

somefunction('a', 1, 'b', 2, 'c', 3, 'd', 4);
Run Code Online (Sandbox Code Playgroud)