perl - 正确且可移植的 utf8 文件名规范化

标签 perl utf-8 portability

还有另一个 perl/utf8 问题:

代码:

use 5.012;
use utf8;
use strict;
use warnings;
use feature qw(unicode_strings);

use open qw(:std :utf8);
use Encode qw(encode decode);
use charnames qw(:full);
use Unicode::Normalize qw(NFD NFC);

my $name = "\N{U+00C1}";        # Á (UPPERCASE A WITH ACUTE)

opendir(my $dh, ".") || die "error opendir";
while(readdir $dh) {
    say "ENC-OK" if      decode('UTF-8', $_)   =~ $name; #never true
    say "NFC-OK" if NFC( decode('UTF-8', $_) ) =~ $name; #true
}
closedir $dh;

上面的代码将为包含 Á 的每个文件打印 NFC-OK在文件名中。但是永远不会在 NFD 编码的文件系统上打印 ENC-OK,因为 opendir 永远不会返回 Á以\x00C1 形式,但“A”、“口音”...

问题:如何为任何操作系统正确编写上述代码可移植?

最佳答案

进一步来说,

NFC( decode('UTF-8', $_) ) =~ quotemeta( NFC( $name ) )


NFD( decode('UTF-8', $_) ) =~ quotemeta( NFD( $name ) )

适用于任何形式的文件名。

...嗯,只要它是 UTF-8 编码的。在 Windows 上情况并非如此,除非使用 chcp 65001 时。

关于perl - 正确且可移植的 utf8 文件名规范化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857208/

相关文章:

static - 如何强制使用静态库而不是共享?

perl - 如何解决PintOS无法识别的字符\x16

c++ - 如何在 C/C++ 中将字符串从 UTF8 转换为 Latin1?

python - 如何在另一个 Perl 安装中安装相同版本的模块,就像在 Python 中使用 pip 一样?

具有国际/UTF-8 字符的 Python urllib2() 函数

c++ - Boost.Locale 是否支持读写 UTF-8 编码的文件?

java - java JDK可以移植吗?

c++ - Winsock 2 可移植性

perl - 从脚本中,在远程服务器上运行脚本并获取其输出

perl - 使用 Perl,如何重命名驱动器所有子目录中的文件?