Tags Perl

Quick, what does the following print:

print "Hellon";
print reverse "Hello";

No, it's not:




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 !


comments powered by Disqus