繁体   English   中英

如何在Perl中引用特定的哈希值?

[英]How can I take a reference to specific hash value in Perl?

如何在特定哈希键中创建对值的引用。 我尝试了以下但是$$ 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";

一般来说,如果你想用切片 或参考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:尽管是一个古老的话题,但我决定抛出两分钱,因为我之前看到过我曾经访问过同样的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM