Maverick
Maverick

Reputation: 587

How to print hash of hash in where one hash is reference to other

I am trying to learn complex data structure in perl, for that i i have written a code but i am not getting any output :

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

my %abc=(Education => "BE",Marital_Status => "Single", Age => "28", Working_Exp => "4yrs");
my %cde=(Education => "BE",Marital_Status => "Single", Age => "29", Working_Exp => "5yrs");


my %info =(info_one => "\%abc", info_two => "\%cde");

foreach my $val (keys %info)
{
  foreach my $check ( keys %{$info{val}})
  {
    print ${$info{val}}{check}."\n";
  }
}

Upvotes: 0

Views: 81

Answers (1)

Dan Dascalescu
Dan Dascalescu

Reputation: 152076

For learning complex data structures in Perl, there's no better reference than the Perl Data Structures Cookbook.

The assignments to info_one and info_two are strings, so you want to remove the double quotes from around \%abc and \%cde. Also, you need to add the $ scalar sign to val and check in the last print line, because those are variables.

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

my %abc= (
    Education => "BE",
    Marital_Status => "Single", 
    Age => "28", 
    Working_Exp => "4yrs"
);
my %cde= (
    Education => "BE",
    Marital_Status => "Single", 
    Age => "29", 
    Working_Exp => "5yrs"
);


my %info = (
   info_one => \%abc,
   info_two => \%cde
);

foreach my $val (keys %info) {
    foreach my $check ( keys %{$info{$val}} ) {
        print ${$info{$val}}{$check}."\n";
    }
}

The last line is a little ugly, but as you read through the Data Structures Cookbook, you'll learn to use the -> operator and write the statement more elegantly.

Upvotes: 5

Related Questions