ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
2.16. Converting Between Octal and HexadecimalProblemYou want to convert a string (e.g., " 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. SolutionUse Perl's $number = hex($hexadecimal); # hexadecimal $number = oct($octal); # octal DiscussionThe 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 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 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"; See AlsoThe "Scalar Value Constructors" section in perldata (1) and the "Numeric Literals" section of Chapter 2 of Programming Perl; the |