如何创建对特定哈希键中值的引用。我尝试了以下但 $$foo 是空的。任何帮助深表感谢。
$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";
$foo = \${$hash->{1}};
$hash->{1} = "ONE";
#I want "MONEY: ONE";
print "MONEY: $$foo\n";
如何创建对特定哈希键中值的引用。我尝试了以下但 $$foo 是空的。任何帮助深表感谢。
$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";
$foo = \${$hash->{1}};
$hash->{1} = "ONE";
#I want "MONEY: ONE";
print "MONEY: $$foo\n";
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";
打开严格和警告,你会得到一些关于出了什么问题的线索。
use strict;
use warnings;
my $hash = { a => 1, b => 2, c => 3 };
my $a = \$$hash{a};
my $b = \$hash->{b};
print "$$a $$b\n";
一般来说,如果你想用 slices或 refs做事,你必须使用旧式的、堆积的 sigil 语法来获得你想要的东西。如果您不记得堆积的 sigil 语法详细信息,您可能会发现参考快速参考很方便。
更新
正如murugaperumal指出的那样,你可以做到my $foo = \$hash->{a};
我可以发誓我试过了,但它没有用(令我惊讶)。我会把它归结为疲劳使我更加愚蠢。
一个经典的,但这些例子似乎并不完整,直到你用两种方式来说明它
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:尽管这是一个老话题,但我决定扔掉我的两分钱,因为我看到我以前访问过同样的问题