Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Are defined or // garantee not to autovivify?

by perlfan (Vicar)
on May 31, 2020 at 05:58 UTC ( [id://11117520]=note: print w/replies, xml ) Need Help??


in reply to Are defined or // garantee not to autovivify?

I don't use exists $hashtest{abc} and defined $hashtest{abc} because defined can handle undef. However, sometimes I do defined $hashtest{abc} and $hashtest{abc} because I want the false condition to be based on more than $hashtest{abc} being undef. I also want it to evaluate to false if it's an empty string or 0, in addition to undef. In that case because the second condition is not protected by defined I need to make sure that the key exists. TBH I don't remember the last time I even used exists.

To summarize:

# generally pointless, I would not use the mere existence of the key t +o mean anything; check it's value if ( exists $hashtest{abc} and defined $hashtest{abc} ) { print qq{This is worthless IMO.\n}; }
Rather just do this if undef is taken as does not exist.
if (defined $hashtest{abc}) { print qq{Better than 'exists'; check for the value being undef or no +t undef.\n}; }
And if I want to check the value, something like:
if (defined $hashtest{abc} and $hashtest{abc}) { print qq{Also, better than 'exists' and when I want to make sure the + value is not "falsey"\n}; }

Replies are listed 'Best First'.
Re^2: Are defined or // garantee not to autovivify?
by haukex (Archbishop) on May 31, 2020 at 09:09 UTC
    I do defined $hashtest{abc} and $hashtest{abc} because I want the false condition to be based on more than $hashtest{abc} being undef.

    In that case, simply using $hashtest{abc} in boolean context is enough to cover undef as well. (Personally I'd add the defined test if I'm going to be using an operator that will give me a warning when used with an undef value.)

    I would not use the mere existence of the key to mean anything

    The difference between defined and exists becomes quite significant if one iterates over the hash (keys, values, each).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11117520]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-24 22:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found