如何在Windows中使用Perl创建Unicode文件名

vfh0ocws  于 2023-10-24  发布在  Perl
关注(0)|答案(3)|浏览(244)

我有以下代码

  1. use utf8;
  2. open($file, '>:encoding(UTF-8)', "さっちゃん.txt") or die $!;
  3. print $file "さっちゃん";

但是我得到的文件名是.txt
我想知道是否有一种方法可以让这个工作,因为我会期望(这意味着我有一个unicode文件名)这不诉诸Win32::API,Win32 API::* 或移动到另一个平台,并使用桑巴舞共享修改文件。
目的是确保我们没有任何需要加载的Win32特定模块(即使是有条件的)。

mqxuamgl

mqxuamgl1#

Perl将文件名视为不透明的字节字符串。它们需要按照您的“locale”编码(ANSI代码页)进行编码。
在Windows中,这通常是cp1252。它由GetACP系统调用返回。(前缀“cp”)。但是,cp1252不支持日语字符。
Windows还提供了一个“Unicode”(又名“Wide”)接口,但Perl不提供使用内置插件 * 访问它的功能。Win32::LongPath使用这个宽接口,因此您可以使用它的函数而不是内置插件来避免编码相关的约束。

  • Perl对Windows的支持在某些方面很糟糕。
rfbsl7qr

rfbsl7qr2#

使用Encode::Locale

  1. use utf8;
  2. use Encode::Locale;
  3. use Encode;
  4. open($file, '>:encoding(UTF-8)', encode(locale_fs => "さっちゃん.txt") ) or die $!;
  5. print $file "さっちゃん";
hmtdttj4

hmtdttj43#

下面的代码使用Activestate Perl在Windows 7上生成一个unicoded文件名。

  1. #-----------------------------------------------------------------------
  2. # Unicode file names on Windows using Perl
  3. # Philip R Brenan at gmail dot com, Appa Apps Ltd, 2013
  4. #-----------------------------------------------------------------------
  5. use feature ":5.16";
  6. use Data::Dump qw(dump);
  7. use Encode qw/encode decode/;
  8. use Win32API::File qw(:ALL);
  9. # Create a file with a unicode name
  10. my $e = "\x{05E7}\x{05EA}\x{05E7}\x{05D5}\x{05D5}\x{05D4}".
  11. "\x{002E}\x{0064}\x{0061}\x{0074}\x{0061}"; # File name in UTF-8
  12. my $f = encode("UTF-16LE", $e); # Format supported by NTFS
  13. my $g = eval dump($f); # Remove UTF ness
  14. $g .= chr(0).chr(0); # 0 terminate string
  15. my $F = Win32API::File::CreateFileW
  16. ($g, GENERIC_WRITE, 0, [], OPEN_ALWAYS, 0, 0); # Create file via Win32API
  17. say $^E if $^E; # Write any error message
  18. # Write to the file
  19. OsFHandleOpen(FILE, $F, "w") or die "Cannot open file";
  20. binmode FILE;
  21. print FILE "hello there\n";
  22. close(FILE);
展开查看全部

相关问题