Why is 'print (52-80)*42' different than 'print 42*(52-80)' in Perl?

Perl:: What is:

1. (52-80)*42
2. 42*(52-80)

Ans:

1. -28
2. -1176

Why?

Have fun explaining/justifying this please!

#!/usr/bin/perl
use strict;
print 42*(52-80) , "\n";
print ((52-80)*42) , "\n";
print (52-80)*42 , "\n";
print "\n";
my $i=(52-80)*42;
print $i, "\n";

Output:

> -1176
> -1176-28
> -1176

Answers


If you add use warnings; you'll get:

print (...) interpreted as function at ./test.pl line 5.
Useless use of a constant in void context at ./test.pl line 5

The warning that Alex Howansky aludes to means that

print (52-80)*42 , "\n"

is parsed as

(print(52-80)) * 42, "\n"

which is to say, a list containing (1) 42 times the result of the function print(-28), and (2) a string containing the newline. The side-effect of (1) is to print the value -28 (without a newline) to standard output.

If you need to print an expression that begins with parentheses, a workaround is to prepend it with +:

print +(52-80)*42, "\n"         #  ==> -1176

Thanks to Perl's wacky parsing rules (oh Perl, you kook!), these statements:

print ((52-80)*42) , "\n";
print (52-80)*42 , "\n";

Are interpreted as if they were written:

(print ((52-80)*42)), "\n";
(print (52-80))*42, "\n";

This is why you end up seeing -1176-28 on one line, and the expected blank line is missing. Perl sees (print-expr), "\n"; and simply throws away the newline instead of printing it.


Need Your Help

Xcode 5.1 ld: library not found for -lGoogleAnalyticsServices

xcode compiler-errors google-analytics ios7.1 xcode5.1

Today I updated my Xcode to Xcode 5.1, and now every time I try to compile my code and test it on the simulator I got several errors about architecture 86_64 and Google Analytics Services Library.

How to replace special characters in a string?

java string

I have a string with lots of special characters. I want to remove all those, but keep alphabetical characters.