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


In reply to Re: perl do's and don'ts by CheeseLord
in thread perl do's and don'ts by Anonymous Monk

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.