Dhruv Tyagi Dhruv Tyagi - 1 year ago 40
Perl Question

How do I access array of hash in perl and compare values to the desired string?

Actually i have an array of hash in Perl and i have to iterate every hash value and compared to the desired string for eg:

@AoH = (
husband => "barney",
wife => "betty",
son => "bamm bamm",
husband => "george",
wife => "jane",
son => "elroy",

husband => "homer",
wife => "marge",
son => "bart",

now i have to compare the son value in every iteration.....
what is the best way

Answer Source

You can simply iterate through the array and compare the son every time to your desired string.

my $new_string;
foreach my $entry (@AoH){
  if($entry->{son} eq $desired_string){
    print "Found it.";
    #assigning the value of 'son' to the $new_string
    $new_string = $entry->{son};

In this little example the $desired_string is the string you compare the son value against.

If you're only interested in accessing all the values in all hashes and then search for the pattern you can store the values in a temporary array:

my @tempArray;
foreach my $entry (@AoH){
   push @tempArray, values %{$entry};

if( grep($_ eq $desired_string) @tempArray){
  print "one hash contains the desired string as an value";

I wasn't really sure what you want to achieve, but I hope that I could help a bit further.