简体   繁体   中英

Perl: Copying an array from a hash of hash of arrays

Given a HoHoA

my %FIELDS = (
    LA => {
      NAME => [1],
      ADDRESS => [2,3,4,5],
      TYPE => [6],
      LICENCE => [0],
      ACTIVE => [],
    },
...
);

I'm trying to make a copy of a particular array

my @ADDRESS_FIELDS = @{$FIELDS{$STATE}->{ADDRESS} };

Since everything inside %FIELDS is by reference the arrow de-references the inner hash and the @{} de-references the array. (I understand that the arrow isn't strictly necessary)

print $ADDRESS_FIELDS[3]."\n";
print @ADDRESS_FIELDS."\n";

gives

5
4

The first print behaves as expected but the second one is giving me the scalar value of, I assume, the referenced array instead of a new copy. Where am I going astray?

The concatenation operator forces scalar context on its operands. Use a comma instead:

print @array, "\n";

Note that the elements are separated by $, , which is empty by default.

Or, to separate the array elements by $" (space by default) in the output, use

print "@array\n";

Or, join them yourself:

print join(' ', @array), "\n";
cat my.pl 
#!/bin/perl
#
use strict;
use warnings;
use Data::Dumper;

my %FIELDS = (
    LA => {
        NAME => [1],
        ADDRESS => [2,3,4,5],
        TYPE => [6],
        LICENCE => [0],
        ACTIVE => []
    },
);

my @addy = @{$FIELDS{LA}->{ADDRESS}};
foreach my $i(@addy){
    print "i=$i\n";
}
perl my.pl
i=2
i=3
i=4
i=5
print @ADDRESS_FIELDS."\n";

Evaluates your array in a scalar context and returns the number of elements (which in your case is 4).

print join(', ', @ADDRESS_FIELDS)."\n";

is what you want i guess.

HTH

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