It's no secret at this point that the "problem" is the ORing of strings instead of numbers.

This code fragment derives from discussion about an interview question that asked for a code fragment for determining if a dotted quad IP address was valid. One straightforward solution was basically

if ( ($a,$b,$c,$d) = m/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ ) { if ( $a < 256 && $b < 256 && $c < 256 && $d < 256 ) { return 1; } } return 0;

which works, though there are better ways to parse IPv4 addresses.

In the course of "improving" the solution, someone reached into their bag of tricks and pulled out one often used in assembly language (and occassionaly in C): OR the numbers together and compare once, thus trading off 3 tests and branches against less expensive boolean operations. Unfortunately, Perl's automagic string to number conversion then doesn't happen, and the "improved" expression ORs strings instead of numbers. But, it looks like it should work! And, in one of those amusing quirks that happen now and then, you might not notice the problem if you happened to pick a simple set of test data, such as this one, which tests boundaries and then probes into the middle of the range.

0.0.0.0: "0" | "0" | "0" | "0" eq "0" OK 255.255.255.255: "255" | "255" | "255" | "255" eq "255" OK 127.0.0.1: "127" | "0" | "0" | "1" eq "127" OK

My solution was to force the conversion via

return 1 if (0+$a|0+$b|0+$c|0+$d) < 256;

which tye hinted at above (and pointed out privately) could more simply be written as

return 1 if (0|$a|$b|$c|$d) < 256;

In reply to Re: Can you spot the problem? (solution) by dws
in thread Can you spot the problem? by dws

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.