为什么此路径无法在PERL中打开Windows文件? [英] Why doesn't this path work to open a Windows file in PERL?

查看:64
本文介绍了为什么此路径无法在PERL中打开Windows文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图和Strawberry Perl一起玩,而让我感到困扰的一件事是读取文件.

I tried to play with Strawberry Perl, and one of the things that stumped me was reading the files.

我试图做:

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

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

But it can not find the file (despite the file being there, and no permissions issues).

在Linux上,等效代码(除文件名外,脚本的100%相同)是可以正常工作的.

An equivalent code (100% of the script other than the filename was identical) worked fine on Linux.

推荐答案

按照 Perl常见问题解答5 ,您应该在DOS/Windows文件名中使用正斜杠斜杠(或者,也可以转义反斜杠).

As per Perl FAQ 5, you should be using forward slashes in your DOS/Windows filenames (or, as an alternative, escaping the backslashes).

为什么我不能在DOS路径中使用"C:\ temp \ foo"?为什么C:\ temp \ foo.exe不起作用?

哇!您只需在该文件名中放入一个标签和一个换页符即可!请记住,在双引号字符串("like \ this")中,反斜杠是转义字符.这些的完整列表在perlop中的Quote和类似Quote的运算符中.毫不奇怪,您在旧版DOS文件系统上没有名为"c:(tab)emp(formfeed)oo"或"c:(tab)emp(formfeed)oo.exe"的文件.

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.

要么用单引号引起来,要么(最好)使用正斜杠.由于自MS-DOS 2.0之类以来的所有DOS和Windows版本在路径中都将/和\视为相同,因此您最好使用与Perl不冲突的版本-或POSIX shell,ANSI C和C ++,awk,Tcl,Java或Python,仅举几例.POSIX路径也更可移植.

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:< TAB> est \"的文件数字.txt"

So your code should be open(FH, "D:/test/numbers.txt"); instead, to avoid trying to open a file named "D:<TAB>est\numbers.txt"

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

As an aside, you could further improve your code by using lexical (instead of global named) filehandle, a 3-argument form of open, and, most importantly, error-checking ALL your IO operations, especially open() calls:

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

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

Or, better yet, don't hard-code filenames in IO calls (the following practice MAY have let you figure out a problem sooner):

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

这篇关于为什么此路径无法在PERL中打开Windows文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆