a “reverse” caveat

November 3rd, 2004 at 10:01 pm

Quick, what does the following print:

print "Hellon";
print reverse "Hello";

No, it’s not:

Hello
olleH

But:
:

Hello
Hello

Why ? Well… as many functions in Perl, reverse suffers from the “list context caveat” (TM). It’s a tricky concept in Perl, and I stumble upon it not for the first time (although I’m not a newbie, it still bites me). The correct way would be:

print scalar reverse "Hello";

This only happens with print, btw. If you assign a reverse to a variable, it won’t happen. This is because print expects a list, which tells reverse that it now must return a value in list context, which makes it reverse the order of the list it got, and not the characters in it !

Related posts:

  1. perl annoyance
  2. lesson for today: caveat in C++ line-reading
  3. The Jotto word game - analysis and a Perl implementation

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)