4

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;
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Vinoth Karthick
  • 905
  • 9
  • 27
  • 4
    _Always_ `use strict; use warnings;`! If you did, you’d have seen something like `Reference found where even-sized list expected`. – Biffen Feb 05 '21 at 12:02

2 Answers2

8

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";
toolic
  • 57,801
  • 17
  • 75
  • 117
2

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.

Dave Cross
  • 68,119
  • 3
  • 51
  • 97