GC30 GC30 - 3 months ago 17
Perl Question

For each object in array in perl

I am trying to loop through each object in an array in Perl and I think I am making an obvious error.

my @members_array = [
{
id => 1234,
email => 'first@example.com',
}, {
id => 4321,
email => 'second@example.com',
}
];

use Data::Dumper;
for my $member ( @members_array ) {
print Dumper( $member );
}


Expected output for first iteration

{
id => 1234,
email => 'first@example.com',
}


Actual output for first iteration

[{
'email' => 'first@example.com',
'id' => 1234
}, {
'email' => 'second@example.com',
'id' => 4321
}];


How do I loop through these elements in the array? Thanks!

Answer

[ ... ] is used to create an array reference; you need to use ( ... ) to create an array :

my @members_array = (
    {
        id    => 1234,
        email => 'first@example.com',
    }, {
        id    => 4321,
        email => 'second@example.com',
    }
);

And then the rest of your code will work just fine.