如何在 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";
How do I create a reference to the value in a specific hash key. I tried the following but $$foo is empty. Any help is much appreciated.
$hash->{1} = "one";
$hash->{2} = "two";
$hash->{3} = "three";
$foo = \${$hash->{1}};
$hash->{1} = "ONE";
#I want "MONEY: ONE";
print "MONEY: $foo\n";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
打开严格和警告,您会得到一些关于出了什么问题的线索。
一般来说,如果你想用切片
或获取 refs进行操作,你必须使用旧式的、堆积的 sigil 语法来获得你想要的。如果您不记得堆积的印记语法,您可能会发现参考快速参考很方便细节。更新
正如murugaperumal指出的,你可以做
my $foo = \$hash->{a};
我可以发誓我尝试过但它不起作用(令我惊讶的是)。我会把这归因于疲劳让我变得更加愚蠢。Turn on strict and warnings and you'll get some clues as to what's going wrong.
In general, if you want to do things with slices
or taking refs, you've got to use the old style, piled sigil syntax to get what you want. You may find the References Quick Reference handy, if you don't recall the piled sigil syntax details.update
As murugaperumal points out, you can do
my $foo = \$hash->{a};
I could swear I tried that and it didn't work (to my surprise). I'll chalk it up to being fatigue making me extra foolish.一个经典,但在你以两种方式说明之前,这些例子似乎并不完整
PS:尽管这是一个古老的话题,但我决定扔掉我的两分钱,因为我看到我以前访问过同样的问题
a classic, and yet the examples don't seem to be complete until you illustrate it both ways
PS: despite being an old topic, I decided to throw my two cents, since I saw I've visited this same question before