Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through an array of hashes in Perl

Tags:

perl

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"; }
like image 401
Ricky Avatar asked Jan 20 '11 13:01

Ricky


People also ask

How do you loop through a hash in Perl?

Answer: There are at least two ways to loop over all the elements in a Perl hash. You can use either (a) a Perl foreach loop, or (b) a Perl while loop with the each function. I find the Perl foreach syntax easier to remember, but the solution with the while loop and the each function is preferred for larger hashes.

How do you loop through an array in Perl?

Perl Array with for Loop. A control variable will be passed in for loop as the index of the given array. Output: Perl Array with while Loop. The while loop executes as long as the condition is true. Output: Perl Array with until Loop. The until loop works like while loop, but they are opposite of each other.

Is there a way to loop through a hash of arrays?

You probably don't want to use shift on your array anyway, since that will delete entries from your original structure. If you want to loop through hash of arrays you can do some thing like this Here $array will hold your array values one at a time for a particular key.

What is an array of hashes in Perl?

We used a lot of functionalities in Perl script among that array of hashes is one of the concepts and used less frequently in the application. It is mostly used in big-enterprise data applications to handle a huge amount of datas to store and retrieve the datas in the heap memory. This is a guide to the Perl array of hashes.


1 Answers

@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.

like image 136
mscha Avatar answered Sep 28 '22 06:09

mscha