请选择 进入手机版 | 继续访问电脑版
楼主: Nicolle
1283 13

Perl Cookbook 2nd Edion [推广有奖]

Reader's 发表于 2017-7-21 23:12:42 |显示全部楼层 |坛友微信交流群
  1. Recipe 1.4 Converting Between Characters and Values
  2. 1.4.1 Problem
  3. You want to print the number represented by a given character, or you want to print a character given a number.

  4. 1.4.2 Solution
  5. Use ord to convert a character to a number, or use chr to convert a number to its corresponding character:

  6. $num  = ord($char);
  7. $char = chr($num);
  8. The %c format used in printf and sprintf also converts a number to a character:

  9. $char = sprintf("%c", $num);                # slower than chr($num)
  10. printf("Number %d is character %c\n", $num, $num);
  11. Number 101 is character e
  12. A C* template used with pack and unpack can quickly convert many 8-bit bytes; similarly, use U* for Unicode characters.

  13. @bytes = unpack("C*", $string);
  14. $string = pack("C*", @bytes);

  15. $unistr = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
  16. @unichars = unpack("U*", $unistr);
复制代码

使用道具

Reader's 发表于 2017-7-21 23:14:11 |显示全部楼层 |坛友微信交流群
  1. Recipe 1.5 Using Named Unicode Characters
  2. 1.5.1 Problem
  3. You want to use Unicode names for fancy characters in your code without worrying about their code points.

  4. 1.5.2 Solution
  5. Place a use charnames at the top of your file, then freely insert "\N{CHARSPEC}" escapes into your string literals.
复制代码

使用道具

Reader's 发表于 2017-7-21 23:15:57 |显示全部楼层 |坛友微信交流群
  1. Recipe 1.6 Processing a String One Character at a Time
  2. 1.6.1 Problem
  3. You want to process a string one character at a time.

  4. 1.6.2 Solution
  5. Use split with a null pattern to break up the string into individual characters, or use unpack if you just want the characters' values:

  6. @array = split(//, $string);      # each element a single character
  7. @array = unpack("U*", $string);   # each element a code point (number)
  8. Or extract each character in turn with a loop:

  9. while (/(.)/g) {         # . is never a newline here
  10.         # $1 has character, ord($1) its number
  11.     }
复制代码

使用道具

Reader's 发表于 2017-7-21 23:21:28 |显示全部楼层 |坛友微信交流群
  1. Recipe 1.7 Reversing a String by Word or Character
  2. 1.7.1 Problem
  3. You want to reverse the words or characters of a string.

  4. 1.7.2 Solution
  5. Use the reverse function in scalar context for flipping characters:

  6. $revchars = reverse($string);
  7. To flip words, use reverse in list context with split and join:

  8. $revwords = join(" ", reverse split(" ", $string));
复制代码

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-3-29 06:23