in reply to Re: (MeowChow) Re2: When does $_ get used?
in thread When does $_ get used?

Reading from a file doesn't have the "false false" problem on reading a 0 or empty line because the value read includes the trailing "\n" so will never be empty. As for why "0\n" isn't treated as false, I don't know -- normally the trailing stuff in a string is silently ignored, but (experimenting...) it seems that a string that converts to a value of zero is still true if it has stuff after it other than spaces (and maybe other things -- not tested everything, but not \n so not whitespace in general). But it's still zero in an expression, so "0 " is false, "0 pigs" is true, and 0+"0 pigs" is false. It's one of those places where Perl does what you want, most of the time, but is hard to understand if you want complete details.

—John

  • Comment on Re: Re: (MeowChow) Re2: When does $_ get used?

Replies are listed 'Best First'.
(tye)Re: Why isn't "0\n" false?
by tye (Sage) on Jul 27, 2001 at 11:37 UTC

    No, at least part of your testing was flawed. "0 ", "0\n", "00", and even "0.0" are all true values. The only false values are "" and "0", period. Boolean context does not first convert the scalar to a number. undef is a special case of "" and numeric 0 is a special case "0" (or at least that is one way to think of it).

    The real false values are "" and numeric 0 but "0" is also considered false because otherwise it would get really confusing. (: But there is no way for a numeric zero to get silently promoted to include a string value like "0 " or "0\n". Numeric zero always becomes simply "0", so we don't need to make any other strings false.

            - tye (but my friends call me "Tye")
      Boolean context does not first convert the scalar to a number

      Ah, I see.

      No, at least part of your testing was flawed. "0 ", "0\n", "00", and even "0.0" are all true values. The only false values are "" and "0", period.

      perl -e "print (0+qq(0 )?'true':'false')" perl -e "print (qq(0\n)?'true':'false')"
      What am I doing wrong? It looks like "0 " is indeed false, while "0\n" is true.

      Update: I didn't notice I still had the 0+ in there. I tried a bunch of variations. That's what I get for experimenting at 2am!

      —John

        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")