When I try this code:
use strict;
use warnings;
print (44+66)/2;
It gave me:
Useless use of division (/) in void context at p.pl line 3.
But, after some tries, it worked by adding extra outer parentheses around the expression like:
use strict;
use warnings;
print ((44+66)/2);
And it did work!
Can anybody explain why?
Using Deparse will give you more information about how perl is parsing your code:
perl -MO=Deparse p.pl
Useless use of division (/) in void context at p.pl line 3.
use warnings;
use strict;
print(110) / 2;
p.pl syntax OK
Here you can see that the expression in the parens was evaluated as expected (66+44 = 110). But, then perl passes 110 as input to print
, then tries to divide the output of print
by 2.
Another helpful tool is diagnostics:
perl -Mdiagnostics p.pl
Useless use of division (/) in void context at p.pl line 3 (#1)
(W void) You did something without a side effect in a context that does
nothing with the return value, such as a statement that doesn't return a
value from a block, or the left side of a scalar comma operator. Very
often this points not to stupidity on your part, but a failure of Perl
to parse your program the way you thought it would.
It's great that you enabled warnings
because it alerted you that there could be a problem with your code. When we run the code, we get 110 as output, whereas you expected 55.