Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing Array of Hashes in perl

I have a structure as below:

my $var1 = [{a=>"B", c=>"D"}, {E=>"F", G=>"H"}];

Now I want to traverse the first hash and the elements in it.. How can I do it?

When I do a dumper of $var1 it gives me Array and when on @var1 it says a hash.

like image 889
user2013387 Avatar asked Oct 28 '25 08:10

user2013387


2 Answers

You iterate over the array as you would with any other array, and you'll get hash references. Then iterate over the keys of each hash as you would with a plain hash reference.

Something like:

foreach my $hash (@{$var1}) {
  foreach my $key (keys %{$hash}) {
    print $key, " -> ", $hash->{$key}, "\n";
  }
}
like image 158
Mat Avatar answered Oct 31 '25 05:10

Mat


First off, you're going to trip Perl's strict mode with your variable declaration that includes barewords.

With that in mind, complete annotated example given below.

use strict;

my $test = [{'a'=>'B','c'=>'D'},{'E'=>'F','G'=>'H'}];

# Note the @{ $test }
# This says "treat this scalar reference as a list".
foreach my $elem ( @{ $test } ){
    # At this point $elem is a scalar reference to one of the anonymous
    # hashes
    #
    # Same trick, except this time, we're asking Perl
    # to treat the $elem reference as a reference to hash
    #
    # Hence, we can just call keys on it and iterate
    foreach my $key ( keys %{ $elem } ){
        # Finally, another bit of useful syntax for scalar references
        # The "point to" syntax automatically does the %{ } around $elem
        print "Key -> $key = Value " . $elem->{$key} . "\n";
    }
}
like image 44
Paul Alan Taylor Avatar answered Oct 31 '25 06:10

Paul Alan Taylor