1

It seems my code cannot iterate over an array stored in a hash.

What did I miss ?

#!/usr/bin/env perl
use Data::Dumper;

my $data = {array   => ['a', 'b', 'c']};

my @array = $data->{array};
print Dumper(@array); # It looks like $data->{array} is an array

print "Ref: ".ref($data->{array})."\n"; # And this array is indeed an array

foreach ($data->{array}) { print "$_\n"; } # But this doesn't work        
foreach (@array) { print "$_\n"; } # Neither this one

# But with a regular array it works...
my @myNames = ('Larry', 'Curly', 'Moe');
foreach (@myNames) { print "$_\n"; }

My output:

$VAR1 = [
          'a',
          'b',
          'c'
        ];
$VAR1 = 'a';
Ref: ARRAY
ARRAY(0x8002bcf8)
ARRAY(0x8002bcf8)
Larry
Curly
Moe

I am pretty confused with REF/SCALAR types. Sometime Perl takes values as references sometime not. In this case, because I get 'ARRAY' from the ref function, I guess $->{array} doesn't give me an array but a reference to the array.

I have also tried @$data->{array} without success.

1 Answer 1

2

$data->{array} is indeed an array reference.

To dereference it, use @{} on the reference

foreach (@{$data->{array}}) { print "$_\n"; }

Edit: Or if you dont want to use {...} after @

my $arrayref = $data->{array}; 

foreach (@$arrayref ) { print "$_\n"; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Damned, I've tried @[...] and @(...) but not @{...}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.