【发布时间】:2025-11-23 23:20:03
【问题描述】:
Perl 中确定一个值是字节序列还是编码字符串的标准测试是什么?如果它是一个编码字符串,它是什么字符编码的?
让我们假设以下完整的 Perl 脚本:
'foo';
如何确定这个文字字符串是字节序列还是某种编码的字符串?而如果是某种字符编码的字符串,那它是用什么字符编码的呢?
这个问题与 Unicode 或 UTF-8 无关。通常是关于 Perl 中的字节与字符。这个问题也不是关于自动字符编码检测,这完全是一个不同的话题。
更新
在初始化$letter 之后,我希望Perl 告诉我它认为存储在变量$letter 中的字母在什么字符编码中。我不希望它一定是正确。确保 Perl 理解字母的编码字符是我作为程序员的责任。我明白了。但是应该有一种简单易行的方法来测试 Perl 认为一个字符(或字符串)的字符编码是什么。不是吗?
C:\>perl -E "$letter = 'Ž'; say $letter =~ m/\w/ ? 'matches' : 'does not match'"
does not match
C:\>perl -MEncode -E "$letter = decode('UTF-8', 'Ž'); say $letter =~ m/\w/ ? 'matches' : 'does not match'"
does not match
C:\>perl -MEncode -E "$letter = decode('Windows-1252', 'Ž'); say $letter =~ m/\w/ ? 'matches' : 'does not match'"
matches
C:\>perl -MEncode -E "$letter = decode('Windows-1252', 'Ž'); $letter = encode('Windows-1252', $letter); say $letter =~ m/\w/ ? 'matches' : 'does not match'"
does not match
C:\>chcp
Active code page: 1252
C:\>
Perl 不能按需报告它理解(正确或错误地)存储在$letter 中的值是什么字符编码?
【问题讨论】:
-
@innaM 你可能有兴趣阅读我在 PerlMonks 上的 recent post 关于这个 Stack Overflow 问题及其许多很好的答案。我已经读了很多遍了。