Thursday, July 17, 2014

Guess What This Perl Does

Mark Dominus (author of an advanced Perl book):

A few weeks ago I asked people to predict, without trying it first, what this would print:

perl -le 'print(two + two == five ? "true" : "false")'

(If you haven’t seen this yet, I recommend that you guess, and then test your guess, before reading the rest of this article.)

People familiar with Perl guess that it will print true; that is what I guessed. The reasoning is as follows: Perl is willing to treat the unquoted strings two and five as strings, as if they had been quoted, and is also happy to use the + and == operators on them, converting the strings to numbers in its usual way. If the strings had looked like "2" and "5" Perl would have treated them as 2 and 5, but as they don’t look like decimal numerals, Perl interprets them as zeroes. (Perl wants to issue a warning about this, but the warning is not enabled by default. Since the two and five are treated as zeroes, the result of the == comparison are true, and the string "true" should be selected and printed.

Of course, that’s not what it does.

2 Comments RSS · Twitter


Coming from someone who does not know Perl, literally at all:

My first thought when I see it is: two & five must have been variables. But I quickly discarded that within a few seconds when I realized I was looking at a single self-contained line of code. My second thought was that Perl must attempt to figure out what an unquoted string is (inference typing). If you put in a 5, it would resolve to a number. Two would resolve to a string. In many languages, using the + operator on a string would concatenate. So I would read the line of code as: ("twotwo" == "five" ? "true" : "false"), which would return "false".


It'll try and fail on printing on unopened file handle

Leave a Comment