Perl access value from Hash Reference

1.3k Views Asked by At

In my Perl code, I ended up having a hash reference like below. I would like to access an individual element from it. I tried multiple ways, but I was not able to fetch it.

#!/usr/bin/perl
#use strict;
use Data::Dumper;
my %h={'one'=>1,'two'=>2};
print Dumper($h{'one'});

Output

$VAR1 = undef;
2

There are 2 best solutions below

0
On BEST ANSWER

Use parentheses to construct your hash, not braces:

use strict;
use warnings;
use Data::Dumper;

my %h = ('one'=>1, 'two'=>2);
print Dumper($h{'one'});

Braces are used to construct a hash reference.

Also, add use warnings;, which would have generated a message that there was a problem with your code.


Or, if you really wanted a hashref:

my $h = {'one'=>1, 'two'=>2};
print "$h->{one}\n";
0
On

What you've (accidentally) done there, is to create a hash with a key that is a stringified hash reference and a value that is undef. And perldoc perlref has a section called WARNING: Don't use references as hash keys.