Why is "print (52-80) * 42" different from "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";

Conclusion:

> -1176
> -1176-28
> -1176
+3
source share
3 answers

If you add use warnings;, you will receive:

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

A warning that Alex Howansky suggests that

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

analyzed as

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

that is, a list containing (1) 42 times the result of the function print(-28)and (2) a line containing a new line. A side effect (1) is printing the value -28(without a new line) to standard output.

, , +:

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

Thanks to the Perl wacky parsing rules (about Perl, you kook!), These statements:

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

interpreted as if they were written:

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

This is why you see -1176-28in one line, and the expected empty line is missing. Perl sees (print-expr), "\n";and simply throws a new line instead of printing. A.

+6
source

All Articles