you make 3 checks on the input to see if it contains :
- not digits ( $binary =~/\D.*/ )
- digits if ( $binary =~/\d.*/ ) {
- binary digits next if /0/ || /1/;
cut to the chase. Since the last one contains the crux of your rule, that's the only one you need.
There's no need to use split on the input, either :
@eachnum = split (//, $binary);
A regex will search through the length of the string, so regexing on each digit has (in this case!) the same effect as regexing on the entire string.
Also, if you ever plan on forking one script from another, or evaling some code, you should use die rather than exit. die's error code is trappable, exit is not. This turns into
print("Not a binary number!\n");exit;}
into die ("Not a binary number");
Also, using a newline in die will surpress the line number in the output. This may be handy if you want to hide that from your users.
the exit in your sub is redundant.
In a more general view, all of your variable are global.
You might want to look at perlsub to see how to pass parameters between subs.
however, there are good things, too!
your code ran with modification!
your code uses strict!
and warnings!
you seem to have a decent grasp of the regex character classes.
the convb2d sub works well.
with a little modification, we get :
#!/usr/bin/perl -w
use strict;
print "\n\nEnter a binary number : ";
my $binary=<STDIN>;
chomp ($binary);
die ("not binary") if $binary =~/[^01]/;
&convb2d ($binary);
sub convb2d {
my $num2conv = shift;
my $decimal = unpack
( "N", pack("B32", substr( $num2conv, -32 )));
print ("Decimal: $decimal\n");
exit;
}
#eNd
So with some practice, this can be a 5 line program, and even shorter.these 2 line need to remain the same, you can't remove them. Note that we assign a value to $binary at the same time it gets declared.
print "\n\nEnter a binary number : ";
my $binary=<STDIN>;
remove the newline from $binary and test it. the regex /[^01]/ indicates a negated character class, so anything that's not zero or one. chomp ($binary);
die ("not binary") if $binary =~/[^01]/;
&convb2d ($binary);
Also, you can combine the chomp and the declaraction/assignment of $binary like this : chomp (my $binary=<STDIN>);
but that's a little complex.
Overall, good job. It takes some time to let perl sink in, but the flexibility gained is worthwhile. Have fun learning and try not to get frustrated.
I tried to stay away from things like formatting or use of whitespace; you've probably got a style down that works well for you, and I'd rather help you learn the language than criticize how many returns you have between lines.
update : typo fix. clarified list |