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

Hi Monks,

I am trying to wrap my head around why the following test doesn't behave as I expected it to. I am trying to set a hash to a default boolean value unless the hash key exists. Here's an example:

#!/usr/bin/perl use strict; use warnings; my %hash; $hash{KEY1} = "0"; $hash{KEY1} = "1" unless $hash{KEY1}; print "KEY1 = $hash{KEY1}\n"; # i expect KEY1 = 0 $hash{KEY1} = "FALSE"; $hash{KEY1} = "TRUE" unless $hash{KEY1}; print "KEY1 = $hash{KEY1}\n"; # i expect KEY1 = TRUE
Am I just having a case of the Monday mornings? I thought double quoting "0/1" would result in stringification and not an actual boolean.

Replies are listed 'Best First'.
Re: Hashes and boolean values
by moritz (Cardinal) on Jan 23, 2012 at 13:12 UTC
    I thought double quoting "0/1" would result in stringification and not an actual boolean.

    "0" produces a string, but that is still false in boolean context.

    You should really use exists:

    $hash{KEY1} = '1' unless exists $hash{KEY};
      wouldn't that just autovivify it and then burn me later?

        I don't understand, I thought you wanted to set a default. Now you are afraid that setting a default will burn you?

        I am trying to set a hash to a default boolean value unless the hash key exists. Here's an example:

        That's exactly what my code does.

        I cannot answer whether you will burn later, but exists $hash{foo} will not autovivify $hash{foo}. Now, exists $hash{foo}{bar} will autovivify $hash{foo}, but then, so will EXPR if $hash{foo}{bar}.
Re: Hashes and boolean values
by osbosb (Monk) on Jan 23, 2012 at 13:11 UTC
    Yes, I am having a case of the mondays. Anything that stringifies to an empty string or the string `0` is false. I'll leave this hanging around for reference.
Re: Hashes and boolean values
by Anonymous Monk on Jan 23, 2012 at 16:05 UTC
    “Golfing” is a pasttime.   It’s okay to use more than one statement.