4

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

我怎样才能做到这一点?

4

5 回答 5

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;
于 2009-08-13T16:09:19.880 回答
4

我找到了答案

my %city ;

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

我可以用这种方式生成

于 2009-08-13T09:33:20.623 回答
1

Perl Data Structures Cookbook perldsc可能会有所帮助。它有示例向您展示如何创建通用数据结构。

于 2009-08-14T12:17:02.620 回答
0
my %city ;

如果你想推

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

(0r)

push @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior];
于 2014-03-12T08:54:41.500 回答
0

您可以在此答案中阅读我的简短教程。简而言之,您可以将对哈希的引用放入值中。

%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'
#     ---^
于 2016-03-10T14:42:07.133 回答