我在处理包含非英语字符(Activestate Perl、Windows XP)的路径时遇到困难。如何打开、写入、复制路径中包含希腊语/俄语/法语重音字符的文件?假设我要将text.txt文件复制到的目录是:C:\Documents and Settings\στα\Desktop
use File::Spec;
my $save = File::Spec->canonpath( $mw->chooseDirectory() );
my $file = catfile($save , "renamed_text.txt");
my $input = "üüü\text.txt";
copy ($input, $file) or die "File cannot be copied.";发布于 2010-12-23 21:20:38
我没有特权投票支持Chris Dolan的答案,但我已经用基于Win32::Codepage的相同解决方案解决了日本的路径名问题。
这可能需要确认,但我认为Perl假定所有非ASCII型路径名都是UTF8。在Linux和OS上,这很好用,因为OS路径名是用UTF8编码的。但是,在旧版本的Windows上( Windows 7之前?)路径名以国家/地区的语言环境编码(例如,日本的Shift-jis )。因此,所有返回带有非ASCII字符的路径名的Perl调用都会被搞乱。
我使用的解决方案是使用Win32:Codepage找到区域设置编码,然后在读取文件时将其编码为UTF8。然后,在写入(或更新)文件时,我将解码回区域设置编码。
发布于 2010-12-19 14:10:21
我在几年前的一个项目中遇到了同样的问题(我们的PAR打包的GUI应用程序必须在Shift-JIS编码下工作)。我尝试了很多技术来让Perl 5.8自动完成这项工作。最后,我的乏味但有效的解决方案是在将每个文件名传递给内置程序之前对其进行编码。
首先,设置实用函数:
use Encode;
use Win32::Codepage;
my $encoding = Win32::Codepage::get_encoding() || q{};
if ($encoding) {
$encoding = Encode::resolve_alias($encoding) || q{};
}
sub encode_filename {
my ($filename) = @_;
return $encoding ? encode($encoding, $filename) : $filename;
}然后,随时随地使用它
next if (! -d encode_filename($tmpldir));
my $file = SWF::File->new(encode_filename($dest));
@entries = File::Slurp::read_dir(encode_filename($srcdir));
etc...我甚至写了一个小的检查程序,以确保我在任何地方都使用它!
egrep "\-[a-zA-Z] |open[^_]|[^ ]parse|unlink|symlink|mkdir[^_]|mkpath|rename[^\']|File::Copy::copy|rmtree|getTemplate[^D]|write_file|read_file|read_dir" *.pl `find lib -name '*.pm'` | grep -
v encode_filename | egrep -v '^[^:]+: *(\#|_announce|debug)'如果你错过了一个,你会在运行时得到“宽字符”的警告...
https://stackoverflow.com/questions/4232397
复制相似问题