2009-08-13 47 views
4

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

我怎樣才能達致這?

+0

想要以編程方式創建它還是隻需定義那些一次性的變量? – Salgar 2009-08-13 09:30:47

+0

以編程方式 – Sam 2009-08-13 09:33:37

+1

您是否試圖從某種文件中讀取這些數據?如果是這樣,請提供該文件的簡短示例(隨意刪除真實姓名和地址,自然),以便人們可以看到您正在使用的格式。更一般地說,你應該看一下'perldoc perlreftut'來介紹如何製作和使用引用以及perldoc perldsc'來製作美妙的預製結構食譜。您可以通過終端或在線獲得:http://perldoc.perl.org/index-tutorials.html – Telemachus 2009-08-13 09:34:04

回答

4

我發現像

my %city ; 

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

答案我可以通過這種方式

+1

您是否有此信息一個文件或電子表格或某種數據庫?我懷疑你是否想純粹用你的程序來輸入數據,所以很容易找出數據的結構,然後直接將記錄讀入複雜的數據結構。 (請注意,你已經有一個輸入錯誤 - $ stretch爲$ street。輸入大量數據的手很容易出錯) – Telemachus 2009-08-13 09:36:20

+0

非常感謝你sir – Sam 2009-08-13 09:38:34

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; 
+0

你只需要' - >',你顯然在工作反對參考。因此,這個'$ data - > {'city1'} {'street1'} [0];'也可以工作。 – 2009-08-13 18:02:53

+0

偉大的觀點 - 更新。 – Logan 2015-05-14 20:47:47

1

的Perl數據結構食譜,perldsc,或許能夠提供幫助。它有示例向您展示如何創建通用數據結構。

0
my %city ; 

如果你想推

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

(OR)

push @{ city{ $c_name } { $street } }, [ $name , $no_house , $senior]; 
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' 
#  ---^