Let's do it, but for real -- that is, with warnings on
perl -we'print (1 ? "yes" : "no") . " bar"'
It prints
print (...) interpreted as function at -e line 1.
Useless use of concatenation (.) or string in void context at -e line 1.
yes
(but no newline at the end)
So since (1 ? "yes" : "no")
is taken as the argument list for the print
function then the ternary is evaluated to yes
and that is the argument for print
and so that, alone, is printed. As this is a known "gotcha," which can easily be done in error, we are kindly given a warning for it.
Then the string " bar"
is concatenated (to the return value of print
which is 1
), what is meaningless in void context, and for what we also get a warning.
One workaround is to prepend a +
, forcing the interpretation of ()
as an expression
perl -we'print +(1 ? "yes" : "no") . " bar", "\n"'
Or, call the print
as function properly, with full parenthesis
perl -we'print( (1 ? "yes" : "no") . " bar", "\n" )'
where I've added the newline in both cases.
See this post for a detailed discussion of a related example and precise documentation links.
(print (1 ? 'yes' : 'no')) . ' bar'
, but you are looking forprint ((1? 'yes' : 'no') . ' bar')
-- Operator Precedence and Associativity. – Rhynchocephalian