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

Why this will work

#!/usr/bin/perl -w use utf8; use feature qw( say ); use strict; my $NotEq = undef; say 'string equal undef' if $NotEq == 'something not undef';#

Replies are listed 'Best First'.
Re: perl undef value and eq and ==
by choroba (Archbishop) on Aug 05, 2016 at 05:42 UTC
    == compares numbers. undef as a number is 0, 'something not undef' as a number is 0. 0 == 0 returns true.

    Similarly,

    say q() eq undef; # 1

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: perl undef value and eq and ==
by LanX (Archbishop) on Aug 05, 2016 at 06:12 UTC
Re: perl undef value and eq and ==
by Marshall (Abbot) on Aug 05, 2016 at 15:42 UTC
    As chobora points out, == is designed to compare numbers, not strings.
    If the intent is to compare string values, "eq" or "ne" is the right comparison operator.

    As LanX points out the right way to test for defined or not defined is with the "defined" operator.

    An expression like say q() eq undef;  # 1 will indeed "work", however this will cause a warning if use warnings; is in effect: "use of unitialized value in eq".

    An idiom that I use often in certain types of code is the use of the "//=" operator, like this $string //= '';.

    Maybe there is something like this:

    my ($keyvalue) =~ /someregex (match).../; # If the match fails, $keyvalue is going to "undefined". # Rather than test for that with some kind of "if" statement, $keyvalue //= ''; #does the job
    That will assign $keyvalue to be '' (the null string) if it was "undefined".

    That way I can write  if ($keyvalue eq 'important'){..} without a run-time warning if $keyvalue wasn't defined. The other place that it helps is that I can print $keyvalue without getting a different kind of warning!

    What I'm saying is that sometimes it is a good idea to just convert potentially undefined strings into '', null strings and avoid any explicit conditional logic at all to ask about "defined-ness" and just use an obvious string "eq" or "ne" expression. I think the operator showed up in Perl 5.10, but that's been out there for awhile.