简体   繁体   中英

Perl 2d Array Push

Why is there a difference in the creation of the following arrays @test1 and @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:

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

Dumpt for test2:

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

Is there a possibility to create the same result of @test1 with iterative pushing to @test2?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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