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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With