简体   繁体   English

Perl 2d阵列推送

[英]Perl 2d Array Push

Why is there a difference in the creation of the following arrays @test1 and @test2? 为什么以下数组@ 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);

Datadump for test1: test1的数据转储:

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

Dumpt for test2: test2转储:

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

Is there a possibility to create the same result of @test1 with iterative pushing to @test2? 是否可以通过迭代推送到@ test2来创建与@ test1相同的结果?

Instead of: 代替:

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

You probably want: 您可能想要:

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

The square brackets will create an anonymous array and will return a reference to the new array. 方括号将创建一个匿名数组,并将返回对新数组的引用。 So @test1 will contain a single scalar value which is a reference to an array. 因此, @test1将包含单个标量值,该标量值是对数组的引用。

Also when dumping a structure like an array, it is often clearer to prefix it with a backslash in order to pass a reference: 同样,在转储类似数组的结构时,通常更清楚的是在其前面加上反斜杠以传递引用:

print Dumper(\@test2);

Which gives: 这使:

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

Remember when you pass an array in a Perl function call, the array gets "flattened" into the argument list. 请记住,当您在Perl函数调用中传递数组时,该数组会“展平”到参数列表中。

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

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