gpt4 book ai didi

arrays - Perl - 具有两个数组参数的函数

转载 作者:行者123 更新时间:2023-12-01 15:28:56 24 4
gpt4 key购买 nike

我在使用 Perl 中的函数时遇到问题。

我的函数有 2 个参数,它们是数组:

sub get_coordinate {
my (@array_col, @array_lin) = (@_);

do some stuff
}

我这样调用它:

    $index_col                  = int(rand(10));
$index_lin = int(rand(10));
@array_col = (0,0,0,0,0,0,0,0,0,0);
@array_lin = (0,0,0,0,0,0,0,0,0,0);
$array_col[$index_col] = 1;
$array_lin[$index_lin] = 1;

get_coordinate(@array_col, @array_lin);

我的问题是我收到错误消息:在@array_lin in numeric eq (==) 中使用未初始化的值 switch.pl 第 82 行(#1) (W uninitialized) 一个未定义的值被使用,就好像它已经被使用了一样 定义。它被解释为“”或 0,但也许这是一个错误。 要抑制此警告,请为您的变量分配定义的值。

我不明白为什么 @array_col 被初始化而不是 @array_lin。

当我以这种方式在函数中打印@array_col 和@array_lin 时:

print "@array_col\n@array_lin\n";

我得到:0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0

有什么想法吗?

谢谢,单片机

最佳答案

在 Perl 中,所有列表都是扁平的。这两个列表是等价的。

( 1, 2, ( 3, 4, ( 5 ), (6, 7), 8), (), )
( 1, 2, 3, 4, 5, 6, 7, 8 )

同样的事情也会发生在把几个数组放在一个列表中时。

my @foo = (1, 2, 3);
my @bar = (4, 5, 6);
my @new = (@foo, @bar); # 1, 2, 3, 4, 5, 6

当您将东西传递给函数时,这些东西会变成参数列表。因此,数组最终会出现在同一个列表中,就像上面的 @foo@bar 一样。

frobnicate(@foo, @bar);

当您在列表上下文中分配某些内容时,整个列表将从左到右分配。对于左侧列表中的标量,这意味着它们将获得它们的值。但是一有数组,这个就贪心了。它将吸收所有剩余的值。

my ($one, $two, @rest, $will_be_undef) = (1, 2, 3, 4, 5, 6);

值将像这样分配:

$one = 1;
$two = 2;
@rest = ( 3, 4, 5, 6 );
$will_be_undef = undef;

传递两个数组需要做的是获取引用,并在我们的函数中取消引用它们。

frobnicate( \@foo, \@bar );

sub frobnicate {
my ($first_array, $second_array) = @_;

my @foo = @{ $first_array };
my @bar = @{ $second_array };

...
}

关于arrays - Perl - 具有两个数组参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54903497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com