2016-04-26 101 views
3

%{$var}%$var之间的区别是什么?我想这个代码,但有错误:

each on reference is experimental at test.pl line 21. Type of argument to each on reference must be unblessed hashref or arrayref at test.pl line 21.

use feature 'say'; 

%HoH = (
    1 => { 
     husband => "fred", 
     pal  => "barney", 
    }, 
    2 => { 
     husband => "george", 
     wife  => "jane", 
     "his boy" => "elroy", 
    }, 
    3 => { 
     husband => "homer", 
     wife  => "marge", 
     kid  => "bart", 
    }, 
); 

for ($i = 1; $i <= 3; $i++) { 
    while (($family, $roles) = each %$HoH{$i}) { 
     say "$family: $roles"; 
    } 
} 

但这个代码工作正常:

use feature 'say'; 

%HoH = (
    1 => { 
     husband => "fred", 
     pal  => "barney", 
    }, 
    2 => { 
     husband => "george", 
     wife  => "jane", 
     "his boy" => "elroy", 
    }, 
    3 => { 
     husband => "homer", 
     wife  => "marge", 
     kid  => "bart", 
    }, 
); 

for ($i = 1; $i <= 3; $i++) { 
    while (($family, $roles) = each %{$HoH{$i}}) { 
     say "$family: $roles"; 
    } 
} 
+0

可能重复[在$ {var},“$ var”和“$ {var}”在Bash shell中有什么区别?](http://stackoverflow.com/questions/18135451/what- is-the-the-var-var-and-var-in-the-bash-shell) – Emna

+2

@Emna:OP语言是* Perl * ... – MarcoS

+3

在代码中使用'use strict'。 – eballes

回答

7

随着%$HoH{$i}你做$斛散列引用,而与%{$HoH{$i}}你犯了一个哈希引用$HoH{$i},这就是你想要的...而且,use strict对你的代码:-)

+0

是的,我通常在我的代码中使用strict。这只是为了测试目的。 :d。感谢您的回答。 :) – stenlytw

+2

@bounces,即使在测试中,您也必须使用它!在源代码中使用strict时的错误是非常不同的:'全局符号'$ HoH“需要明确的程序包名称',这会给你提供你的问题的答案。 – eballes

+0

@eballes但是仍然有一个错误,“每个参考都是实验性的”,严格使用。 – stenlytw

2

由于解析的优先级不同哈希与下标散列。它适用于第二个版本 - %{ $HoH{$i} } - 因为您明确指出$HoH{$i}查找返回的值本身就是一个hashref。

%$HoH{$i}被解释为%{ $HoH }{$i} - 即。在将表达式$HoH解释为hashref之后发生下标 - 事实并非如此。 %HoH是一个散列,但不使用$HoH - 即未定义。