2017-08-11 83 views
1

引用混亂雖然看着 http://perl.plover.com/FAQs/references.htmlPerl中使用散列值是陣列

從下面,我真不明白 @{ $table{$state} }

它解釋說,這是哈希表,其中的關鍵是$state和值數組..所以這基本上是 正常%table和其值將數組..這是正確的方式來看待這個?

難道還有%{ $table{$state} }這樣的事嗎?我甚至不知道這是否意味着什麼。

1 while (<>) { 
2 chomp; 
3 my ($city, $state) = split /, /; 
4 push @{$table{$state}}, $city; 
5 } 
6 
7 foreach $state (sort keys %table) { 
8 print "$state: "; 
9 my @cities = @{$table{$state}}; 
10  print join ', ', sort @cities; 
11 print ".\n"; 
12 } 
+0

請檢查['HoA'](http://perldoc.perl.org/perldsc.html#HASHES-OF-ARRAYS)和['HoH'](http://perldoc.perl.org/perldsc。 html#HASHES-OF-HASHES) –

回答

3

@{ }是取消引用。它的意思是預期$table{$state}是一個數組引用。 如果有在那裏散列引用,而不是一個數組引用

#!/usr/bin/env perl 

use strict; 
use warnings; 

my %table = (
    firstkey => [ 1, 2, 3 ], 
    secondkey => [ 'fish', 'bird', 'bat' ], 
); 


foreach my $key (keys %table) { 
    print $key, " is ", ref ($table{$key}), " with a value of ", $table{$key}, "\n"; 

    foreach my $value (@{$table{$key}}) { 
     print "\t$value\n"; 
    } 
} 

%{ $table{$state} }會工作。

所以:

#!/usr/bin/env perl 

use strict; 
use warnings; 

my %table = (
    firstkey => { fish => 1, bird => 2, bat => 3 } 
); 


foreach my $key (keys %table) { 
    print $key, " is ", ref ($table{$key}), " with a value of ", $table{$key}, "\n"; 

    foreach my $subkey (keys %{$table{$key}}) { 
     print "$subkey => $table{$key}{$subkey}\n" 
    } 
} 

這樣做的核心是向下的perl如何實現多維數據結構 - 它通過在子陣列的單個「值」存儲的引用這樣做。

+0

很清楚..謝謝!! – user3502374