You want to convert a string (e.g., "0x55
" or "0755
") containing an octal or hexadecimal number to the correct number.
Perl only understands octal and hexadecimal numbers when they occur as literals in your programs. If they are obtained by reading from files or supplied as command-line arguments, no automatic conversion takes place.
Use Perl's oct
and hex
functions:
$number = hex($hexadecimal); # hexadecimal $number = oct($octal); # octal
The oct
function converts octal numbers with or without the leading "0
": "0350
" or "350
". In fact, it even converts hexadecimal ("0x350
") numbers if they have a leading "0x
". The hex
function only converts hexadecimal numbers, with or without a leading "0x
": "0x255
", "3A
", "ff
", or "deadbeef
". (Letters may be in upper- or lowercase.)
Here's an example that accepts a number in either decimal, octal, or hex, and prints that number in all three bases. It uses the oct
function to convert from octal and hexadecimal if the input began with a 0. It then uses printf
to convert back into hex, octal, and decimal as needed.
print "Gimme a number in decimal, octal, or hex: "; $num = <STDIN>; chomp $num; exit unless defined $num; $num = oct($num) if $num =~ /^0/; # does both oct and hex printf "%d %x %o\n", $num, $num, $num;
The following code converts Unix file permissions. They're always given in octal, so we use oct
instead of hex
.
print "Enter file permission in octal: "; $permissions = <STDIN>; die "Exiting ...\n" unless defined $permissions; chomp $permissions; $permissions = oct($permissions); # permissions always octal print "The decimal value is $permissions\n";
The "Scalar Value Constructors" section in perldata (1) and the "Numeric Literals" section of Chapter 2 of Programming Perl; the oct
and hex
functions in perlfunc (1) and Chapter 3 of Programming Perl.