我尝试使用 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:
顺便说一句,您可以通过使用词法(而不是全局命名)文件句柄、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/