When you print it with warnings it becomes clear(er)
perl -we'print (2 & 2), "\n"'
says
print (...) interpreted as function at -e line 1.
Useless use of a constant ("\n") in void context at -e line 1.
It works out print (2&2)
as a function call to print
† and duly prints 2 (no newline!), and then it keeps evaluating the comma operator, with "\n"
in void context next, which it also warns us about.
With >> 1
also there, the return 1
of print (2&2)
(for success) is bit shifted to 0
, which disappears into the void, and we get
another "Useless use of ... in void context."
One fix is to add a +
since what follows it must be an expression
perl -we'print +(2 & 2) >> 1, "\n"'
Or, make a proper call to print
, with parenthesis around the whole thing
perl -we'print((2 & 2) >> 1, "\n")'
Both print a line with 1
.
This is mentioned in print, and more fully documented in Terms and List operators and in Symbolic Unary operators, both in perlop. For another, related, example see this post.
† It also warns about it as it is likely an error -- with a space before parens; no space, no warning.
perl -w
) – Aldineuse warnings;
or-Mwarnings
), not-w
, as-w
also can affect modules you use that you have no control over. – Subdued