开发者

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

How do I create开发者_Go百科 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";


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";


Turn on strict and warnings and you'll get some clues as to what's going wrong.

use strict;
use warnings;

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

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

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.


a classic, and yet the examples don't seem to be complete until you illustrate it both ways

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: despite being an old topic, I decided to throw my two cents, since I saw I've visited this same question before

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜