in reply to Re: (tye)Re: Why isn't "0\n" false?
in thread When does $_ get used?

0+"0 " is the same as 0 which is false. "0 " is true. Likewise 0+"0\n" is false while "0\n" is true.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re: (tye)Re2: Why isn't "0\n" false?
by John M. Dlugosz (Monsignor) on Jul 27, 2001 at 19:54 UTC
    "0 " is true

    So, pray tell me, why does the line I showed print "false"?

    —John

Re: (tye)Re2: Why isn't "0\n" false?
by John M. Dlugosz (Monsignor) on Jul 27, 2001 at 22:35 UTC
    Oops, I edited the wrong line, and didn't notice I still had the 0+ in there. I'm sure we all know how that goes...☺

    But, here's another question. A value is not converted when boolean context is needed, OK. But what if it is a value that has both numeric and string "slots" filled? Which does it use? My guess is it looks at the string, so that "0 but true" is still true even after it's been used in a numeric expression (filling the number slot with 0).

    —John

      Yes, it looks at the string. Like you said, it can't look at the number part or:

      my $val= "0 "; my $dummy= 0+$val; print "True\n" if $val;
      would print "True". This is recorded in the source code in at least 4 places (for speed reasons). Each version boils down to these tests, in order:
      1. undef is false
      2. (references are true unless they reference a destroyed thing)
      3. strings are false if-and-only-if they are "" or "0"
      4. integers are false if-and-only-if they are 0 (zero)
      5. reals are false if-and-only-if they are 0.0 (zero)

      That second item is in parens because it only occurs in one copy of this algorithm. It doesn't matter much because I think the only way to get a reference to a destroyed item is during "global destruction".

      But it did make me curious about a possible low-impact bug which turned out to not exist because of something more interesting: Every time you use a reference in a string context, the resulting string is reconstructed from scratch. When you use a number in a string context, the string representation of that number is computed and then cached inside the scalar so future uses of that (formerly number-only) scalar in a string context don't have to repeat that work. This optimization is not applied to references.

              - tye (but my friends call me "Tye")