【问题标题】:How can I take a reference to specific hash value in Perl?如何引用 Perl 中的特定哈希值?
【发布时间】:2011-01-31 13:39:32
【问题描述】:
如何创建对特定哈希键中值的引用。我尝试了以下但 $$foo 是空的。非常感谢任何帮助。
$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";
$foo = \${$hash->{1}};
$hash->{1} = "ONE";
#I want "MONEY: ONE";
print "MONEY: $$foo\n";
【问题讨论】:
标签:
perl
hash
reference
dereference
【解决方案1】:
经典之作,但在你用两种方式说明之前,这些例子似乎并不完整
use strict;
use warnings;
my $hash = { abc => 123 };
print $hash->{abc} . "\n"; # 123 , of course
my $ref = \$hash->{abc};
print $$ref . "\n"; # 123 , of course
$hash->{abc} = 456;
print $$ref . "\n"; # 456 , change in the hash reflects in the $$ref
$$ref = 789;
print $hash->{abc} . "\n"; # 789 , change in the $$ref also reflects in the hash
PS:尽管这是一个老话题,但我决定扔掉我的两分钱,因为我看到我以前访问过同样的问题
【解决方案2】:
打开严格和警告,你会得到一些关于出了什么问题的线索。
use strict;
use warnings;
my $hash = { a => 1, b => 2, c => 3 };
my $a = \$$hash{a};
my $b = \$hash->{b};
print "$$a $$b\n";
一般来说,如果你想用切片或获取引用来做事,你必须使用旧式的,堆积的印记语法来得到你想要的。如果您不记得堆积的印记语法详细信息,您可能会发现 References Quick Reference 很方便。
更新
正如 murugaperumal 指出的那样,你可以这样做 my $foo = \$hash->{a}; 我可以发誓我试过了,但没有成功(令我惊讶)。我会把它归结为疲劳让我更加愚蠢。
【解决方案3】:
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";