Perl ord 函数
最后修改于 2025 年 4 月 4 日
Perl 的 ord
函数返回字符串第一个字符的 ASCII 或 Unicode 数值。它对于字符编码至关重要。
ord
是 chr
的逆函数,chr
用于将数字转换为字符。它在 Perl 中同时支持 ASCII 和 Unicode 字符。
基本 ord 用法
使用 ord
的最简单方法是处理单个字符的字符串。
basic.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; my $char = 'A'; my $code = ord($char); print "The ASCII code of '$char' is $code\n";
我们演示了 ord
将字符转换为其 ASCII 值。该函数返回第一个字符的数字代码点。
$ ./basic.pl The ASCII code of 'A' is 65
处理 Unicode
ord
可处理超出 ASCII 范围的 Unicode 字符。
unicode.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; use utf8; my $char = '€'; my $code = ord($char); print "The Unicode code point of '$char' is U+", sprintf("%04X", $code), "\n";
此脚本展示了 ord
如何处理 Unicode 欧元符号。我们将输出格式化为十六进制 Unicode 代码点。
$ ./unicode.pl The Unicode code point of '€' is U+20AC
多个字符
ord
只处理多字符字符串的第一个字符。
multichar.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; my $text = 'Perl'; my $code = ord($text); print "The code of first character in '$text' is $code\n"; print "First character is '", chr($code), "'\n";
当给定一个较长的字符串时,ord
只检查第一个字符。我们使用 chr
来演示反向转换。
$ ./multichar.pl The code of first character in 'Perl' is 80 First character is 'P'
比较字符
ord
可用于字符比较和排序。
compare.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; my @chars = ('z', 'a', 'M', '9', '!'); my @sorted = sort { ord($a) <=> ord($b) } @chars; print "Original: @chars\n"; print "Sorted by code: @sorted\n";
我们使用 ord
按 ASCII 值对字符进行排序。这显示了不同字符类型的数字顺序。
$ ./compare.pl Original: z a M 9 ! Sorted by code: ! 9 M a z
字符大小写转换
ord
可以帮助实现自定义的大小写转换逻辑。
case.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; sub to_upper { my $char = shift; my $code = ord($char); return $code >= 97 && $code <= 122 ? chr($code - 32) : $char; } my $lower = 'h'; my $upper = to_upper($lower); print "'$lower' in uppercase is '$upper'\n";
此示例演示了如何使用 ord
检查小写字母的 ASCII 值,并通过调整代码将其转换为大写。
$ ./case.pl 'h' in uppercase is 'H'
验证输入
ord
可以验证用户输入中的字符范围。
validate.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; print "Enter a digit (0-9): "; my $input = <STDIN>; chomp $input; my $code = ord($input); if (length($input) == 1 && $code >= 48 && $code <= 57) { print "Valid digit entered: $input\n"; } else { print "Invalid input. Please enter a single digit.\n"; }
我们使用 ord
通过检查其代码点是否在数字范围(48-57)内来验证输入是否为单个 ASCII 数字。
$ ./validate.pl Enter a digit (0-9): 5 Valid digit entered: 5
创建字符表
ord
有助于生成字符代码表。
table.pl
#!/usr/bin/perl use strict; use warnings; use v5.34.0; print "ASCII Table (32-126):\n"; print "Dec Hex Char\n"; for my $i (32..126) { my $char = chr($i); printf "%3d %02X %s\n", $i, $i, $char eq ' ' ? 'SPACE' : $char; }
此脚本使用 ord
和 chr
生成 ASCII 表。它显示十进制、十六进制和字符值。
$ ./table.pl ASCII Table (32-126): Dec Hex Char 32 20 SPACE 33 21 ! 34 22 " ... 126 7E ~
最佳实践
- 理解编码:了解您正在处理的是 ASCII 还是 Unicode。
- 检查字符串长度:
ord
只处理第一个字符。 - 与 chr 结合使用:与
chr
结合进行转换。 - 记录范围:注释数字范围以提高可读性。
来源
本教程介绍了 Perl 的 ord
函数,并通过实际示例演示了字符到代码点的转换。
作者
列出 所有 Perl 教程。