Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle command line arguments with different radices in Perl

When used as literals in a Perl program, numbers are handled in the same way as in C: "0x" prefix means hexadecimal, "0" prefix means octal, and no prefix means decimal:

$ perl -E 'print 0x23 . "\n"'
35
$ perl -E 'print 023 . "\n"'
19
$ perl -E 'print 23 . "\n"'
23

I would like to pass command line arguments to Perl using the same notation. e.g. If I pass 23, I want to convert the string argument to a decimal value (23). If I pass 0x23, I want to convert to a hexadecimal value (35), and 023 would be converted to octal (19). Is there a built-in way to handle this? I am aware of hex() and oct(), but they interpret numbers with no prefix to be hex/oct respectively (not decimal). Following this convention, it seems that I want a dec() function, but I don't think that exists.

like image 823
FazJaxton Avatar asked Dec 26 '22 02:12

FazJaxton


1 Answers

From http://answers.oreilly.com/topic/419-convert-binary-octal-and-hexidecimal-numbers-in-perl/:

print "Gimme an integer in decimal, binary, octal, or hex: ";
$num = <STDIN>;
chomp $num;
exit unless defined $num;
$num = oct($num) if $num =~ /^0/; # catches 077 0b10 0x20
printf "%d %#x %#o %#bn", ($num) x 4;
like image 164
DVK Avatar answered Feb 19 '23 11:02

DVK