9

I'm a total Perl newbie, so forgive me if this is really stupid, but I can't figure this out. If I have an array like this:

my @array = (
  {username => 'user1', email => 'user1@email' },
  {username => 'user2', email => 'user2@email' },
  {username => 'user2', email => 'user3@email' }
);

What's the most simple way to loop through this array? I thought something like this would work:

print "$_{username} : $_{email}\n" foreach (@array);

But it doesn't. I guess I'm too stuck with a PHP mindset where I could just do something like:

foreach ($array as $user) { echo "$user['username'] : $user['email']\n"; }

1 Answer 1

28

@array contains hash references, so you need to use -> to derefecence.

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

See also the documentation, for instance perldoc perlreftut and perldoc perlref.

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

2 Comments

Oh god, I feel so dumb now. Thank you!
also could be written say "$$_{username} : $$_{email}" for @array;

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.