6

I am trying to check if a hash key exists, for example:

use warnings;
use strict;
use feature qw(say);
use Data::Dump qw(dump);

my $h={a=>1,b=>2};

dump($h);

if (exists $h->{a}{b}) {
  say "Key exists.";
}
dump($h);

This gives:

{ a => 1, b => 2 }
Can't use string ("1") as a HASH ref while "strict refs" in use at ./p.pl line 12.

What is the reason for this error message?

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • use `ref` to check for hashref - http://stackoverflow.com/questions/1267706/why-do-i-get-cant-use-string-as-a-hash-ref-error-when-i-try-to-access-a-hash – erickb Oct 14 '14 at 06:57
  • 1
    Kudos for using [`Data::Dump`](https://metacpan.org/pod/Data::Dump). Just a note, the module exports the `dd` method by default, which you can use to print to STDOUT. The `dump` method is meant for serializing a data structure to a variable. However, when called in a void context it does behave the same as `dd`, which I didn't know until observing your usage here. – Miller Oct 14 '14 at 21:27

1 Answers1

11

$h->{a}{b} implies that value of $h->{a} is hashref, and you want to check if key b for it exists.

Since $h->{a} is simple scalar (1) it can not be used as hashref (use strict prevents it), and thus message Can't use string (“1”) as a HASH ref

mpapec
  • 50,217
  • 8
  • 67
  • 127