ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.4. Converting Between ASCII Characters and ValuesProblemYou want to print out the number represented by a given ASCII character, or you want to print out an ASCII character given a number. SolutionUse $num = ord($char); $char = chr($num); The $char = sprintf("%c", $num); # slower than chr($num)
printf("Number %d is character %c\n", $num, $num);
A @ASCII = unpack("C*", $string); $STRING = pack("C*", @ascii); DiscussionUnlike low-level, typeless languages like assembler, Perl doesn't treat characters and numbers interchangeably; it treats strings and numbers interchangeably. That means you can't just assign characters and numbers back and forth. Perl provides Pascal's $ascii_value = ord("e"); # now 101 $character = chr(101); # now "e" If you already have a character, it's really represented as a string of length one, so just print it out directly using printf("Number %d is character %c\n", 101, 101); The @ascii_character_numbers = unpack("C*", "sample"); print "@ascii_character_numbers\n"; Here's how to convert from HAL to IBM: $hal = "HAL"; @ascii = unpack("C*", $hal); foreach $val (@ascii) { $val++; # add one to each ASCII value } $ibm = pack("C*", @ascii); print "$ibm\n"; # prints "IBM" The See AlsoThe |