[英]How can I create a hash of hashes in Perl?
I am new to Perl. 我是Perl的新手。 I need to define a data structure in Perl that looks like this:
我需要在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 ]
How can I acheive this? 我该如何实现这一目标?
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;
I found the answer like 我找到了答案
my %city ;
$city{$c_name}{$street} = [ $name , $no_house , $senior];
i can generate in this way 我可以用这种方式生成
my %city ;
If you want to push 如果你想推
push( @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior] );
(0r) (0R)
push @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior];
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'
# ---^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.