Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Can you spot the problem? (solution)

by dws (Chancellor)
on Mar 05, 2004 at 23:09 UTC ( [id://334403]=note: print w/replies, xml ) Need Help??


in reply to Can you spot the problem?

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://334403]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-23 22:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found