我该如何在Perl中创建哈希的哈希?

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 ]

我该如何实现这个目标?

你想通过编程创建它还是仅仅定义那些变量一次性使用? - Salgar
1
你是否正在尝试从某种文件中读取这些数据?如果是这样,请提供该文件的简短示例(自然可以删除真实姓名和地址),以便人们可以看到您正在使用的格式。更一般地,您应该查看 perldoc perlreftut,了解如何制作和使用引用的入门讨论,以及 perldoc perldsc,了解预制结构的精彩食谱。您可以通过终端或在线获取两者:http://perldoc.perl.org/index-tutorials.html - Telemachus
是的,我正在从数据库中读取数据并进行数据库编程。 - Sam
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;

你只需要使用 ->,当你明显是在使用引用时。所以 $data->{'city1'}{'street1'}[0]; 同样可以工作。 - Brad Gilbert

4
我找到了答案,就像这样:
my %city ;

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

我可以用这种方式生成。

1
你是否有这些信息的文件、电子表格或数据库?我怀疑你不想仅仅使用程序进行数据输入,因此更容易的方法是先弄清楚数据结构,然后直接将记录读入复杂的数据结构中。(请注意,你已经有一个错别字——$stret应为$street。手动输入大量数据非常容易出错。) - Telemachus

1
Perl数据结构食谱perldsc可能会有所帮助。它提供了示例,展示如何创建常见的数据结构。

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

0
my %city ;

如果你想要推送

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

(0r)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接