当前位置:  开发笔记 > 编程语言 > 正文

为什么对于包含非ASCII字符的文件名,-e文件存在测试总是返回false?

如何解决《为什么对于包含非ASCII字符的文件名,-e文件存在测试总是返回false?》经验,为你挑选了1个好方法。

我正在使用Perl对其名称中包含非ASCII字符的文件进行存在检查.即使文件存在,检查也始终返回false.我在Windows 10机器上使用Strawberry Perl v5.24.0.

这是我的代码:

use strict;
use warnings;

use Encode;

my $file = ' / áéíóú.mov';
if (-e $file) {
  print "$file exists";
} else {
  print " $file does not exists" ;
}

我还通过运行更改了cmd shell中的代码页chcp 65001.然后cmd能够识别字符但不知何故它总是返回此文件的"Not Exists".

我怎样才能解决这个问题?



1> ikegami..:
use strict;
use warnings;

# Properly decode source code, which is expected to be UTF-8.
# This allows non-ASCII characters in the source.
use utf8;

# Properly decode text received from STDIN.
# Properly encode text sent to STDOUT and STDERR.
use Win32 qw( );
my ( $enc_in, $enc_out, $enc_syscall );
BEGIN {
   $enc_input   = 'cp'.Win32::GetConsoleCP();
   $enc_output  = 'cp'.Win32::GetConsoleOutputCP();
   $enc_syscall = 'cp'.Win32::GetACP();

   binmode STDIN,  ":encoding($enc_input)";
   binmode STDOUT, ":encoding($enc_output)";
   binmode STDERR, ":encoding($enc_output)";
}

use Encode qw( encode );

my $file = 'áéíóú.mov';

if (-e encode($enc_syscall, $file, Encode::FB_CROAK | Encode::LEAVE_SRC)) {
   print("$file exists\n");
}
elsif ($!{ENOENT}) {
   print("$file doesn't exist\n");
}
else {
   die("Can't determine if \"$file\" exists: $!\n");
}

要么

use strict;
use warnings;

# Properly decode source code, which is expected to be UTF-8.
# This allows non-ASCII characters in the source.
use utf8;

# Properly decode text received from STDIN.
# Properly encode text sent to STDOUT and STDERR.
use Win32 qw( );
my ( $enc_in, $enc_out, $enc_syscall );
BEGIN {
   $enc_input   = 'cp'.Win32::GetConsoleCP();
   $enc_output  = 'cp'.Win32::GetConsoleOutputCP();
   $enc_syscall = 'cp'.Win32::GetACP();

   binmode STDIN,  ":encoding($enc_input)";
   binmode STDOUT, ":encoding($enc_output)";
   binmode STDERR, ":encoding($enc_output)";
}

use Win32::Unicode::File qw( statW );

my $file = 'áéíóú.mov';

if (statW($file)) {
   print("$file exists\n");
}
elsif ($!{ENOENT}) {
   print("$file doesn't exist\n");
}
else {
   die("Can't determine if \"$file\" exists: $^E\n");
}

后者不仅限于包含机器ANSI字符集字符的路径.

推荐阅读
我我檬檬我我186
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有