1

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!

1 Answer 1

3

[ ... ] 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, spot on, and how annoying! Thanks!
It happens! A fresh eye often helps, I'm glad mine did.

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.