Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

I need to check if a value is true and if it is, I have to replace to something else.
What I have works but it is giving me a lot of warnings when the code runs:
Use of uninitialized value in string ne at myfile.pl.

Here is what I am using to test:
if($data->{classes} ne '') { $data->{classes} =~ s/XY//g; }
Any suggestions?
Thanks for looking!

Replies are listed 'Best First'.
Re: Check for hash ref emptiness
by AnomalousMonk (Archbishop) on Feb 07, 2018 at 22:41 UTC

    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:  <%-{-{-{-<

Re: Check for hash ref emptiness
by NetWallah (Canon) on Feb 07, 2018 at 21:53 UTC
    The regex check will do nothing if the value is empty, so your 'if' check is unnecessary.

    Instead of checking for 'empty', you should be checking 'defined-ness' - which , for a hash uses 'exists':

    if ( exists $data->{classes} and defined $data->{classes} ){ $data->{classes} =~ s/XY//g; }
    UPDATE: Added 'defined' check, per comment by AnomalousMonk(++), below.

                    Python is a racist language what with it's dependence on white space!

      ... you should be checking 'defined-ness' - which , for a hash uses 'exists' ...

      A hash key may exist and its value be undefined. If it is undefined, a warning will be produced by an operation like matching if warnings are enabled — as we hope they (almost) always are! See exists.


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