2012-08-07 66 views
15

我在看下面的代碼演示嵌套的哈希值:爲什麼使用大括號初始化一些哈希值,還有一些使用括號?

my %HoH = (
    flintstones => { 
     husband => "fred", 
     pal  => "barney", 
    }, 
    jetsons => { 
     husband => "george", 
     wife  => "jane", 
     "his boy" => "elroy", # Key quotes needed. 
    }, 
    simpsons => { 
     husband => "homer", 
     wife  => "marge", 
     kid  => "bart", 
    }, 
); 

爲什麼是它最上面的散列(首發1)使用括號被初始化,而子哈希使用大括號初始化?

來自python背景我必須說Perl很奇怪:)。

回答

21

來自Perl背景我發現Perl也很奇怪。

使用圓括號初始化散列(或數組)。散列是一組字符串和一組標量值之間的映射。

%foo = ("key1", "value1", "key2", "value2", ...); # % means hash 
%foo = (key1 => "value1", key2 => "value2", ...); # same thing 

牙套被用來定義一個散列參考。所有引用都是標量值。

$foo = { key1 => "value1", key2 => "value2", ... }; # $ means scalar 

哈希是標量值。由於散列中的值必須是是標量,因此不可能將散列用作另一個散列的值。

%bar = (key3 => %foo);  # doesn't mean what you think it means 

但是我們可以使用散列引用作爲另一個散列的值,因爲散列引用是標量。

$foo = { key1 => "value1", key2 => "value2" }; 
%bar = (key3 => $foo); 
%baz = (key4 => { key5 => "value5", key6 => "value6" }); 

而這就是爲什麼你會看到帶有花括號的列表的圓括號。

+4

只是爲了完整性......而這是真的,'KEY3 =>%foo'沒有做什麼,似乎,'KEY3 => \%foo'增加了一個參考並且是一種非常簡單的方式來使其按照人們的意願去做在那種情況下。 – 2012-08-07 06:06:58

2

首先,parens什麼都不做,只是在這裏改變優先順序。它們與列表創建,哈希創建或哈希初始化無關。您可以使用括號周圍散創作的運算數,

{ (a => 1, b => 2) } 

,你可以忽略周圍的賦值運算符的操作數的括號時,優先允許。

sub f { return a => 1, b => 2 } 
my %hash = f(); 

其次,一個不使用初始化{ }散列;使用它創建一個散列。 { }相當於my %hash;,除了散列是匿名的。換句話說,

{ EXPR } 

是基本相同

do { my %anon = EXPR; \%anon } 

(但不創建一個詞彙範圍)。

匿名散列允許一個寫的

my %HoH = (
    flintstones => { 
     husband => "fred", 
     pal  => "barney", 
    }, 
    jetsons => { 
     husband => "george", 
     wife  => "jane", 
     "his boy" => "elroy", 
    }, 
    simpsons => { 
     husband => "homer", 
     wife  => "marge", 
     kid  => "bart", 
    }, 
); 

代替

my %flintstones = (
    husband => "fred", 
    pal  => "barney", 
); 
my %jetsons = (
    husband => "george", 
    wife  => "jane", 
    "his boy" => "elroy", 
); 
my %simpsons = (
    husband => "homer", 
    wife  => "marge", 
    kid  => "bart", 
); 
my %HoH = (
    flintstones => \%flinstones, 
    jetsons  => \%jetsons, 
    simpsons => \%simpsons, 
); 
6

的本質區別(....)用於創建散列。 {....}被用於創建哈希參考

my %hash = (a => 1 , b => 2) ; 
my $hash_ref = { a => 1 , b => 2 } ; 

在稍微詳細 - {....}使得一個匿名散列並返回與該至極被asigned爲標量的參考$hash_ref

編輯給多一點細節