繁体   English   中英

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

[英]How can I create a hash of hashes in Perl?

我是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 ]

我该如何实现这一目标?

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

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;

我找到了答案

my %city ;

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

我可以用这种方式生成

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

my %city ;

如果你想推

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

(0R)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM