At 09:50 AM 2/20/2006 -0500, D D Allen wrote:
And then try to explain these lines -- why the first produces the output
10 and the second produces the output 30 -- which is not a Perl bug.
print (5*2)*3;
print "\n";
print 5*(2*3);
print "\n";
As Larry Wall says in the Camel book: If it looks like a function, Perl
will treat it as such. So, in the first line, Perl sees first:
print (5*2)
which very much looks like a function call (i.e. function name followed
by arguments within parenthesis). It then interprets the line as the
return value of that print function call (which will be 1 if it
succeeded) multiplied by 3. But this is like saying:
10*3;
on a statement by itself, which is useless, and so it is thrown away.
It still prints the multiplication of 5*2, though, because that's what
print does. However, this is most likely not what you wanted.
If you enable warnings, you'll know immediately that something is wrong,
as the compiler would complain with:
print (...) interpreted as function
Useless use of multiplication (*) in void context
The third line is interpreted as you would expect because, it doesn't
"look" like a function, so the stuff that follows "print" is taken as
the full parameter to it: the multiplication is performed, and the
output submitted to the print() function.
To avoid this, it is usually a good idea to just wrap all function
parameters around parenthesis when there could be doubt as to what are
the actual parameters to it. So if you would have said:
print ((5*2)*3);
there wouldn't be any problem.
Note that this is not a Perl bug, but a nuance of the flexibility of the
language and its syntactic sugar. Other languages avoid these
ambiguities by forcing you to use parenthesis on all function calls, all
the time. But then everything will look like computer code, instead of
the nice and fluid, human legible syntax that is achievable when writing
good Perl.
dZ.
_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs