Sam
Sam

Reputation: 95

How can I create a hash of hashes in Perl?

I am new to Perl. I need to define a data structure in Perl that looks like this:

  city 1 -> street 1 - [ name , no of house , senior people ]
            street 2 - [ name , no of house , senior people ]


  city 2 -> street 1 - [ name , no of house , senior people ]
            street 2 - [ name , no of house , senior people ]

How can I acheive this?

Upvotes: 4

Views: 5776

Answers (5)

Eugen Konkov
Eugen Konkov

Reputation: 25113

You may read my short tutorial at this answer. In short you may put reference to hash into the value.

%hash = ( name => 'value' );
%hash_of_hash = ( name => \%hash );
#OR
$hash_of_hash{ name } =  \%hash;


# NOTICE: {} for hash, and [] for array
%hash2 = ( of_hash => { of_array => [1,2,3] } );
#                  ---^          ---^
$hash2{ of_hash }{ of_array }[ 2 ]; # value is '3'
#     ^-- lack of -> because declared by % and ()


# same but with hash reference
# NOTICE: { } when declare
# NOTICE: ->  when access
$hash_ref = { of_hash => { of_array => [1,2,3] } };
#        ---^
$hash_ref->{ of_hash }{ of_array }[ 2 ]; # value is '3'
#     ---^

Upvotes: 0

Logan
Logan

Reputation: 267

Here is an another example using a hash reference:

my $data = {
    city1 => {
        street1 => ['name', 'house no', 'senior people'],
        street2 => ['name','house no','senior people'],
    },
    city2 => {
        street1 => etc...
        ...
    }
};

You then can access the data the following way:

$data->{'city1'}{'street1'}[0];

Or:

my @street_data = @{$data->{'city1'}{'street1'}};
print @street_data;

Upvotes: 5

Lakshmaiah
Lakshmaiah

Reputation: 1

my %city ;

If you want to push

push( @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior] );

(0r)

push @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior];

Upvotes: 0

brian d foy
brian d foy

Reputation: 132748

The Perl Data Structures Cookbook, perldsc, may be able to help. It has examples showing you how to create common data structures.

Upvotes: 1

Sam
Sam

Reputation: 95

I found the answer like

my %city ;

 $city{$c_name}{$street} = [ $name , $no_house , $senior];

i can generate in this way

Upvotes: 4

Related Questions