Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: perl do's and don'ts

by CheeseLord (Deacon)
on Jun 28, 2001 at 20:59 UTC ( [id://92374]=note: print w/replies, xml ) Need Help??


in reply to perl do's and don'ts

Well, you seem to have the conversion down good (unless I really don't know what I'm doing), but I think you've got far too much code. :) A lot of your testing (as mirod says) could be simplified. Here's what I came up with:

use strict; sub bin2dec { my $arg = shift; return unpack("N", pack("B32", substr("0" x 32 . $arg, -32 ))); } my ($binary, $decimal); print "Please enter a binary number: "; do { chomp ($binary = <STDIN>) } until (length $binary); die "That's not a binary number, dude...\n" if ($binary =~ /[^01]/); $decimal = bin2dec $binary; print "$binary = $decimal\n";

My test is similar to mirod's, but it works by checking to see if there's anything besides 1 and 0, instead of if everything is 1 or 0. I also have the program wait until something is actually entered on the line... but these things are subject to personal taste, IMO.

You'll notice, though, that my bin2dec sub doesn't use any global variables... you'll want to stay away from doing that except in certain situations, as it makes your code less adaptable later on.

That all being said, though, it's not bad code, it's just difficult to understand with the myriad of unnecessary tests in there. I hope that helps... if you've got any more questions, get an account and /msg me! :)

His Royal Cheeziness

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 12:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found