【问题标题】:difference between the following two codes of [ and ( in perl?perl 中 [ 和 ( 的以下两个代码之间的区别?
【发布时间】:2021-01-15 00:47:30
【问题描述】:

当我想将输入文件分配给数组时,我收到了这个错误。

while (<>) {
my @tmp = split;
push my @arr,[@tmp];
print "@arr\n";
}

output: ARRAY(0x7f0b00)
        ARRAY(0x7fb2f0)

如果我将[ 更改为(,那么我将获得所需的输出。

while (<>) {
my @tmp = split;
push my @arr,(@tmp);
print "@arr\n";

output: hello, testing the perl
        check the arrays.

(@tmp)[@tmp] 之间的区别是什么?

【问题讨论】:

    标签: arrays perl multidimensional-array reference


    【解决方案1】:

    普通括号()除了改变优先级之外没有特殊功能。它们通常用于限制列表,例如my @arr = (1,2,3) 方括号返回一个数组引用。在您的情况下,您将构建一个二维数组。 (如果您的代码没有损坏,您会这样做)。

    你的代码也许应该这样写。请注意,您需要在循环块之外声明数组,否则它将不会保留先前迭代的值。另请注意,您不需要使用@tmp 数组,只需将split 放在push 内即可。

    my @arr;                    # declare @arr outside the loop block
    while (<>) {
        push @arr, [ split ];   # stores array reference in @arr
    }
    for my $aref (@arr) {
        print "@$aref";         # print your values
    }
    

    这个数组的结构如下:

    $arr[0] = [ "hello,", "testing", "the", "perl" ];
    $arr[1] = [ "check", "the", "arrays." ];
    

    如果您希望防止输入行混淆,这是一个好主意。否则所有值都在数组的同一级别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多