dave
dave

Reputation: 51

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

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

Upvotes: 5

Views: 5040

Answers (3)

arhak
arhak

Reputation: 2542

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

Upvotes: 3

daotoad
daotoad

Reputation: 27183

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.

Upvotes: 5

muruga
muruga

Reputation: 2122

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

Upvotes: 8

Related Questions