2010-03-25 56 views
5

如何創建對特定哈希鍵值的引用。我嘗試了以下,但$$ foo是空的。任何幫助深表感謝。如何在Perl中引用特定的哈希值?

$hash->{1} = "one"; 
$hash->{2} = "two"; 
$hash->{3} = "three"; 

$foo = \${$hash->{1}}; 
$hash->{1} = "ONE"; 

#I want "MONEY: ONE"; 
print "MONEY: $$foo\n"; 
+0

如果你的散列鍵都是正整數,你應該使用一個數組。 – daotoad 2010-03-25 15:52:54

回答

5

打開嚴格和警告,你會得到一些線索,什麼是錯的。

use strict; 
use warnings; 

my $hash = { a => 1, b => 2, c => 3 }; 
my $a = \$$hash{a}; 
my $b = \$hash->{b}; 

print "$$a $$b\n"; 

在一般情況下,如果你想要做切片 或服用參 的事情,你必須使用舊的風格,堆印記語法來得到你想要的。如果您不記得堆積的sigil語法細節,您可能會發現References Quick Reference方便。

更新

由於murugaperumal指出,你可以做my $foo = \$hash->{a};我可以發誓,我試過了,它沒有工作(我驚奇)。我會把它當成疲勞讓我變得更加愚蠢。

8
use strict; 
use warnings; 
my $hash; 

$hash->{1} = "one"; 
$hash->{2} = "two"; 
$hash->{3} = "three"; 

my $foo = \$hash->{1}; 
$hash->{1} = "ONE"; 
print "MONEY: $$foo\n";