in reply to perl do's and don'ts
intoprint("Not a binary number!\n");exit;}
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.die ("Not a binary number");
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 :
So with some practice, this can be a 5 line program, and even shorter.#!/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
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.
remove the newline from $binary and test it. the regex /[^01]/ indicates a negated character class, so anything that's not zero or one.print "\n\nEnter a binary number : "; my $binary=<STDIN>;
Also, you can combine the chomp and the declaraction/assignment of $binary like this :chomp ($binary); die ("not binary") if $binary =~/[^01]/; &convb2d ($binary);
but that's a little complex.chomp (my $binary=<STDIN>);
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
|
|---|