Related Items  

Linux and Windows IT Support  

We make IT Support easy!

Windows, Apple and Linux IT support and services.

Login or Register  

If you wish to contribute an article, please login or register.

Iterate through Hash of Hashes

PrintE-mail

perl logoHere's how you would iterate through multidimensional hashes in Perl:

Create a hash first:

#!/usr/bin/perl
use warnings;
use strict;

my %HoH = (
    flintstones => {
        husband   => "fred",
        wife   => "wilma",
        pal   => "barney",
    },
    jetsons => {
        husband   => "george",
        wife      => "jane",
        "his boy" => "elroy",  # Key quotes needed.
    },
    simpsons => {
        husband   => "homer",
        wife      => "marge",
        kid       => "bart",
    },
);

Then iterate through it:

foreach my $family (keys %HoH) {
    while (my ($key, $value) = each %{ $HoH{$family} } ) {
        print "$key = $value \n";
    }
}

Other operations

Insert another set of values:

$HoH{ mash } = {
    captain  => "pierce",
    major    => "burns",
    corporal => "radar",
};

Access particular value:

print $HoH{flintstones}{wife}; # will output "wilma"

Set value of a particular key:

$HoH{$flintstones}->{wife} = "jane"; #give Fred a new wife

 


Comments (2)
re: Possible Syntax Error
2 Monday, 22 February 2016 11:19
Ant
Thank you for pointing it out. I've corrected the code.
Possible Syntax Error
1 Friday, 12 February 2016 09:34
Byron Jones
I think the line:

while (my ($key, $value) = each %{ $hash{$family} } ) {

uses $hash, where it should be using $HoH. $hash doesn't seem to be defined or set elsewhere.

Add your comment

Your name:
Subject:
Comment:
  The word for verification. Lowercase letters only with no spaces.
Word verification:
yvComment v.1.24.0
   
Copyright © 1999 - 2017 Virtual Helpme | Business IT Support | Original Template: Allrounder
-->