Home > OS >  How to iterate an array just retrieved from a hash?
How to iterate an array just retrieved from a hash?

Time:12-12

I'm trying to iterate an array which I just retrieved from a hash:

my %h = (
  'z' => ['1', '2', '3'],
  'b' => ['x', 'y'],
);
my @a = $h{'b'};
foreach my $k (@a) {
  print "[$k]";
}

However, instead of [x][y] it prints:

[ARRAY(0x7fc6f2825de8)]

Why?

CodePudding user response:

Since:

'b' => ['x', 'y']

Then:

my @a = $h{'b'};

Is the same as

my @a = ['x', 'y'];

Which is an array where the first element of the array is another array. Its a two-dimensional array.

If you want to print the array in one go, you have to dereference the second level:

print @$k;

If you do not want it to be two-dimensional, you can use dereference it when assigning:

my @a = @{ $h{'b'} };

Be aware that this will not deep copy your hash values.

Or better yet, just copy the reference:

my $aref = $h{'b'};

for my $k (@$aref) {
    print "[$k]";
}
  •  Tags:  
  • perl
  • Related