windows - 为什么此路径无法在 PERL 中打开 Windows 文件?

标签 windows perl io backslash path-separator

我尝试使用 Strawberry Perl,但让我感到困惑的其中一件事是阅读文件。

我尝试过:

open(FH, "D:\test\numbers.txt");

但是它找不到文件(尽管文件在那里,并且没有权限问题)。

等效代码(除文件名外,脚本 100% 相同)在 Linux 上运行良好。

最佳答案

根据 Perl FAQ 5 ,您应该在 DOS/Windows 文件名中使用正斜杠(或者,作为替代方案,转义反斜杠)。

Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?

Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings ("like\this"), the backslash is an escape character. The full list of these is in Quote and Quote-like Operators in perlop. Unsurprisingly, you don't have a file called "c:(tab)emp(formfeed)oo" or "c:(tab)emp(formfeed)oo.exe" on your legacy DOS filesystem.

Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated / and \ the same in a path, you might as well use the one that doesn't clash with Perl--or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too.

所以你的代码应该是 open(FH, "D:/test/numbers.txt"); 而不是试图打开一个名为 "D:est\numbers .txt”


顺便说一句,您可以通过使用词法(而不是全局命名)文件句柄、open 的 3 参数形式来进一步改进您的代码,最重要的是,对所有 IO 操作进行错误检查,尤其是 open () 调用:

open(my $fh, "<", "D:/test/numbers.txt") or die "Could not open file: $!";

或者,更好的是,不要在 IO 调用中对文件名进行硬编码(以下做法可能会让您更快地找出问题):

my $filename = "D:/test/numbers.txt";
open(my $fh, "<", $filename) or die "Could not open file $filename: $!";

关于windows - 为什么此路径无法在 PERL 中打开 Windows 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265749/

相关文章:

windows - 用于在 Windows 上进行符号链接(symbolic link)转换的 Git Hook

c# - 如何在计算机锁定时按键盘键

perl - 在perl中解析制表符分隔的文件

mysql - 使用 Class::DBI 和带连字符的表名

java - 在java中连接到共享驱动器

c - 从标准中读取并写入套接字

windows - 如何在两个日期和时间时间戳之间执行算术运算(加,减)?

windows - 将可能包含非 ASCII Unicode 字符的 PowerShell 输出解码为 Python 字符串

perl - 使用 Sub::Quote 弱化捕获

java - Java6 中 java.nio.file.Path 的替代方案,以实现操作系统文件系统灵活性