A short while back I was called in to look at some Perl code that didn't seem to be working right. The script in question had originally been supplied by a vendor, then gotten hacked to pieces by various people in my group, who are by and large Java programmers.

Which might explain the following chunk of code I discovered:

my $param = $cgi->param('foo'); if ($param != null){ # ... do stuff }

Since I now spend most of my time in Java as well, it took me a couple of seconds to realize the common idiom variable != null is completely inappropriate in Perl. Without strictures, perl was parsing the condition as $param "not equal to" the string 'null'. Certainly not the intended semantics.

Still, it seemed to me that Perl was conveniently Doing What I/We Meant. If foo was passed in (and its value would almost certainly never be 'null'), then $param didn't equal 'null', and the conditional block would execute. Our problem was that the conditional block was not executing. What was going on here?

Later on the drive home, the light bulb came on. The condition was doing a numerical comparison (!=), not a string comparison! So:

$param != null # becomes... $param != "null" # becomes ... $param != 0
Given that $param only contained straight text (no digits), its numerical value would always be 0. Hence the conditional would never execute.

Anyway, I got a kick out of this. Perl's DWIMmery can be a powerful tool, but also a dangerous hazard in the wrong hands. Swiss Army Chainsaw indeed -- just make sure you stand clear!


In reply to The Swiss Army Chainsaw... Watch out for your legs there, buddy! by crashtest

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.