繁体   English   中英

Perl 2d阵列推送

[英]Perl 2d Array Push

为什么以下数组@ test1和@ test2的创建有区别?

#!/bin/perl -w
use Data::Dumper;
use warnings;
use strict;

my @test1 = [
     ['note', 1],
     ['note', 3]
];

print Dumper(@test1);

my @test2;
push(@test2, ['note', 1]);
push(@test2, ['note', 3]);

print Dumper(@test2);

test1的数据转储:

$VAR1 = [
      [
        'note',
        1
      ],
      [
        'note',
        3
      ]
    ];

test2转储:

$VAR1 = [
          'note',
          1
        ];
$VAR2 = [
          'note',
          3
        ];

是否可以通过迭代推送到@ test2来创建与@ test1相同的结果?

代替:

my @test1 = [
     ['note', 1],
     ['note', 3]
];

您可能想要:

my @test1 = (
     ['note', 1],
     ['note', 3]
);

方括号将创建一个匿名数组,并将返回对新数组的引用。 因此, @test1将包含单个标量值,该标量值是对数组的引用。

同样,在转储类似数组的结构时,通常更清楚的是在其前面加上反斜杠以传递引用:

print Dumper(\@test2);

这使:

$VAR1 = [
      [
        'note',
        1
      ],
      [
        'note',
        3
      ]
    ];

请记住,当您在Perl函数调用中传递数组时,该数组会“展平”到参数列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM