in reply to Check for hash ref emptiness

A hash key may or may not exist. (Update: If a hash key does not exist, its value is not defined.) If it exists, its value may or may not be defined. If its value is defined, it may or may not be true. Here are some ways to test if a key exists and its value is true. The first test (test A) is not sufficient.

c:\@Work\Perl\monks>perl -wMstrict -le "my $hr = { foo => undef }; ;; warn qq{test A: 'foo' exists, undefined \n}; if (exists $hr->{foo}) { $hr->{foo} =~ /bar/; } ;; warn qq{test B: 'foo' exists, undefined \n}; if (exists $hr->{foo} && defined $hr->{foo}) { $hr->{foo} =~ /bar/; } ;; warn qq{test C: 'foo' exists, undefined \n}; if ($hr->{foo}) { $hr->{foo} =~ /bar/; } ;; $hr = {}; warn qq{test D: 'foo' does NOT exist \n}; if ($hr->{foo}) { $hr->{foo} =~ /bar/; } " test A: 'foo' exists, undefined Use of uninitialized value in pattern match (m//) at -e line 1. test B: 'foo' exists, undefined test C: 'foo' exists, undefined test D: 'foo' does NOT exist

Update: See True or False? A Quick Reference Guide; Truth and Falsehood in perlsyn.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: Check for hash ref emptiness
by Anonymous Monk on Feb 08, 2018 at 00:08 UTC