Vinoth Karthick
Vinoth Karthick

Reputation: 1087

Perl access value from Hash Reference

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;

Upvotes: 4

Views: 1995

Answers (2)

Dave Cross
Dave Cross

Reputation: 69244

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.

Upvotes: 2

toolic
toolic

Reputation: 62037

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

Upvotes: 8

Related Questions