fortuneman
Technical User
Wrote a little loop to calculate the dec from binary. Problem is that the !$bin matches if $bin is "null" or "zero". I don't want it to match zero. I need a way to get zero to pass through but I'm unsure of an easy way to do this. Additionally, chomp complains too if $bin is null as well. Appreciate any assistance. Thanks.
Code:
use strict;
my $bin= shift;
chomp($bin);
my @answer;
my $dec = 0;
if (!$bin|| $bin !~ (/^[01]*$/)) {
print "Usage: decTobin.pl <decimal value>";
exit(0);
}
@answer = split(//, $bin);
find_dec(@answer);
print $dec;
###########
#Find binary position
###########
sub find_dec{
my $count = 0;
foreach (reverse(@answer)) {
$dec = ($dec + ($_ * (2**$count)));
$count++
}
}