[comp.lang.perl] Perl garbles numeric expression in print

friedman@chekov.UU.NET (Barry Friedman) (06/15/90)

My son asked me to do the following arithmetic:

	6 + 3 X 2 - 7 / 2 X 1 + 9

To which I too quickly responded 14.5 as if he had read me the question
(It was written).  He then claimed that I did not understand "today's
math" because the answer should have been 11.5.  Heh, heh, I said,
you want me to evaluate this like a computer, and I tried to explain the
origin of the precedence rules he had been taught. I explained that
I had figured it as if it had been written  (((((6+3)*2)-7)/2)*1)+9

Watch this, I said as I typed the expression into my favorite interpreter:

BF1> perl -e 'print (((((6+3)*2)-7)/2)*1)+9,"\n";' 
5.5BF2> 

What the heck is going on here I said and tried:

BF2> perl -e 'print ((((((6+3)*2)-7)/2)*1)+9),$/;'
14.5BF3> 

Hmm, no new line on that one but the calculation is correct. How about:

BF3> perl
$a=(((((6+3)*2)-7)/2)*1)+9;
print $a,$/;
14.5

Now that looks a little better.

"Computers are dumb, he said.  Do a lot of programs make mistakes like
that?"

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (06/15/90)

In article <2518@bnr-fos.UUCP> friedman@chekov.UUCP (Barry Friedman) writes:
: My son asked me to do the following arithmetic:
: 
: 	6 + 3 X 2 - 7 / 2 X 1 + 9
: 
[...]
: 
: Watch this, I said as I typed the expression into my favorite interpreter:
: 
: BF1> perl -e 'print (((((6+3)*2)-7)/2)*1)+9,"\n";' 
: 5.5BF2> 
: 
: What the heck is going on here I said and tried:
: 
: BF2> perl -e 'print ((((((6+3)*2)-7)/2)*1)+9),$/;'
: 14.5BF3> 
: 
: Hmm, no new line on that one but the calculation is correct. How about:
: 
: BF3> perl
: $a=(((((6+3)*2)-7)/2)*1)+9;
: print $a,$/;
: 14.5
: 
: Now that looks a little better.
: 
: "Computers are dumb, he said.  Do a lot of programs make mistakes like
: that?"

It's not a mistake.  It's the consequence of a rule that, believe it or not,
actually simplifies things.

If any unary or LIST operator is followed by a left paren, that paren and
its associated closing paren are taken to surround all the arguments of
the operator, as if it were a normal function.  Basically, it's an extension
of the rule "When in doubt, parenthesize," since the parens force it to a
known precedence (that is, the very highest).

This was not the case in Perl 2.0, and much confusion resulted.  The
occasional confusion caused by the overloading of parentheses seems
to be worth it, on the whole, but you do need to know that rule.

The workaround is to parenthesize the whole arg list, as you did, or put
a + in front of the first paren, which has no effect.

This is documented somewhere in the manual page (sic).

Larry