如何在Perl中创建哈希散列?

时间:2009-08-13 08:53:58

标签: perl data-structures hash-of-hashes

我是Perl的新手。我需要在Perl中定义一个如下所示的数据结构:

  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 ]

我怎样才能实现这个目标?

5 个答案:

答案 0 :(得分:5)

以下是使用哈希引用的另一个示例:

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

然后您可以通过以下方式访问数据:

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

或者:

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

答案 1 :(得分:4)

我找到了答案,如

my %city ;

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

我可以用这种方式生成

答案 2 :(得分:1)

Perl数据结构手册perldsc可能会提供帮助。它有一些示例向您展示如何创建公共数据结构。

答案 3 :(得分:0)

my %city ;

如果你想推

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

(OR)

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

答案 4 :(得分:0)

您可以在this回答中阅读我的简短教程。简而言之,您可以将哈希引用到值中。

%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'
#     ---^