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"; }
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.
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.
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With