When answering your earlier question, I forgot that Win32.pm provides a decent interface. I will go back and that answer. However, for your immediate problem, what you need to do is not to automatically die
when the CreateDirectory
call fails, but to check the error code. If the error code is 0xb7
(ERROR_ALREADY_EXISTS
), you go on your merry way.
The problem is that it is hard to go on your merry way using Perl functions when you have a Unicode file name. The solution is to use Win32::GetANSIPath
(just keep an eye on the full length of the path):
#!/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";
Oh, and, good luck deleting that directory.
In a serious vein, though, the whole Windows Unicode file operations thing is a bit of a mess.
As far as I understand these things, you need the ANSI path name if you want to be able to use Perl functions such as open
to work with paths containing Unicode characters. E.g.:
my $file = catfile($dir_name, 'test.txt');
open my $fh, '>', $file
or die "cannot create '$file': $!";
will fail whereas
my $file = catfile($ansi_path, 'test.txt');
open my $fh, '>', $file
or die "cannot create '$file': $!";
will succeed (at least on my system). You do not need the ANSI paths if you are going to only use Win32 API functions to deal with files (and that might be easier in your case). There are a bunch of modules to help you with the latter on CPAN.