开发者

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

开发者 https://www.devze.com 2023-01-18 06:34 出处:网络
Perl:: What is: 1. (52-80)*42 2. 42*(52-80) Ans: 1. -28 2. -1176 Why? Have fun explaining/justifying 开发者_运维技巧this please!

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消