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

I think I'm missing a basic scalar context concept here... What is it exactly that Perl is trying to "subtract" when it prints '0' for unquoted strings like the one below?
$foo = same-as; print $foo;

Replies are listed 'Best First'.
Re: Strings & Scalar Context
by John M. Dlugosz (Monsignor) on Sep 08, 2001 at 00:51 UTC
    barewords become strings. "same"-"as" is 0-0 according to atoi, which reads up to the first non-digit then stops without error (e.g. "99 balloons" => 99).

    —John

      So why '0' instead of undefined ('') in the same-as instance?
        Because minus wants numbers and gives a number as a result. So the two parameters are converted to numbers (both zero) and the result is 0. Then print want's a string, so the 0 is converted to "0" which hits your output stream.

        —John

Re: Strings & Scalar Context
by dga (Hermit) on Sep 08, 2001 at 01:02 UTC

    Try inserting this at the top of your code.

    use strict;

    It will catch barewords like these and a host of other gotchas.

    Update: Added requested explanation of why/how atoi.

    strict is your good friend who will keep you out of a lot of trouble.

    atoi is the C language function ascii to integer which perl uses internally to convert strings to numbers.

    You had a - in your code so Perl converted both arguments to numbers (hence the atoi) and then subtracted them and saved the result in $foo.

    Hope that makes it clearer.

      Thanks for the tip. I understand the bareword issue. What I (didn't know I) was looking for was the atoi explanation.