GC30
GC30

Reputation: 45

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 => '[email protected]',
    }, {
        id    => 4321,
        email => '[email protected]',
    }
];

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

Expected output for first iteration

{
    id    => 1234,
    email => '[email protected]',
}

Actual output for first iteration

[{
    'email' => '[email protected]',
    'id' => 1234
 }, {
    'email' => '[email protected]',
    'id' => 4321
}];

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

Upvotes: 1

Views: 587

Answers (1)

Dada
Dada

Reputation: 6626

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

my @members_array = (
    {
        id    => 1234,
        email => '[email protected]',
    }, {
        id    => 4321,
        email => '[email protected]',
    }
);

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

Upvotes: 3

Related Questions