views:

55

answers:

2

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";
+2  A: 

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.

daotoad
+6  A: 
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";
muruga