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

vfh0ocws  于 8个月前  发布在  Perl
关注(0)|答案(3)|浏览(89)

我有以下代码

use utf8;
open($file, '>:encoding(UTF-8)', "さっちゃん.txt") or die $!;
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

use utf8;
use Encode::Locale;
use Encode;

open($file, '>:encoding(UTF-8)', encode(locale_fs => "さっちゃん.txt") ) or die $!;
print $file "さっちゃん";
hmtdttj4

hmtdttj43#

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

#-----------------------------------------------------------------------
# Unicode file names on Windows using Perl
# Philip R Brenan at gmail dot com, Appa Apps Ltd, 2013
#-----------------------------------------------------------------------

use feature ":5.16";
use Data::Dump qw(dump);
use Encode qw/encode decode/;
use Win32API::File qw(:ALL);

# Create a file with a unicode name

my $e  = "\x{05E7}\x{05EA}\x{05E7}\x{05D5}\x{05D5}\x{05D4}".
         "\x{002E}\x{0064}\x{0061}\x{0074}\x{0061}"; # File name in UTF-8
my $f  = encode("UTF-16LE", $e);  # Format supported by NTFS 
my $g  = eval dump($f);           # Remove UTF ness
   $g .= chr(0).chr(0);           # 0 terminate string
my $F  = Win32API::File::CreateFileW
 ($g, GENERIC_WRITE, 0, [], OPEN_ALWAYS, 0, 0); # Create file via Win32API
say $^E if $^E;                   # Write any error message

# Write to the file

OsFHandleOpen(FILE, $F, "w") or die "Cannot open file";
binmode FILE;                       
print FILE "hello there\n";       
close(FILE);

相关问题