在回答您之前的问题时,我忘记了Win32.pm 提供了一个不错的界面。我会回去那个答案。但是,对于您眼前的问题,您需要做的不是在CreateDirectory调用失败时自动die,而是检查error code。如果错误代码是0xb7 (ERROR_ALREADY_EXISTS),那你就快点走吧。
问题是当你有一个 Unicode 文件名时,你很难继续使用 Perl 函数。解决方案是使用Win32::GetANSIPath(只需注意路径的全长):
#!/usr/bin/perl
use strict; use warnings;
use utf8;
use Encode qw( encode );
use File::Slurp;
use File::Spec::Functions qw( catfile );
use Win32;
use Win32::API;
use constant ERROR_ALREADY_EXISTS => 0xb7;
my $dir_name = 'Волгогра́д';
unless ( Win32::CreateDirectory($dir_name) ) {
my $err = $^E;
if ( $err == ERROR_ALREADY_EXISTS ) {
warn "Directory exists, no problem\n";
}
else {
die Win32::FormatMessage($^E);
}
}
my $ansi_path = Win32::GetANSIPathName($dir_name);
warn "$ansi_path\n";
哦,祝你删除那个目录好运。
不过,严肃地说,整个 Windows Unicode 文件操作有点混乱。
据我了解,如果您希望能够使用诸如 open 之类的 Perl 函数来处理包含 Unicode 字符的路径,则需要 ANSI 路径名。例如:
my $file = catfile($dir_name, 'test.txt');
open my $fh, '>', $file
or die "cannot create '$file': $!";
会失败而
my $file = catfile($ansi_path, 'test.txt');
open my $fh, '>', $file
or die "cannot create '$file': $!";
会成功(至少在我的系统上)。如果您打算只使用 Win32 API 函数来处理文件,则不需要 ANSI 路径(在您的情况下这可能更容易)。在CPAN 上有很多模块可以帮助您处理后者。