为什么此路径无法在 PERL 中打开 Windows 文件?
我尝试使用 Strawberry Perl,但困扰我的事情之一就是读取文件。
我尝试这样做:
open(FH, "D:\test\numbers.txt");
但它找不到该文件(尽管该文件在那里,并且没有权限问题)。
等效代码(除文件名之外的脚本 100% 相同)在 Linux 上运行良好。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据 Perl FAQ 5,您应该在 DOS/Windows 文件名中使用正斜杠(或者,作为替代方案,转义反斜杠)。
因此,您的代码应该是est\numbers.txt”的文件 顺便说一句
open(FH, "D:/test/numbers.txt");
,以避免尝试打开名为“D:,您可以通过使用词法(而不是全局命名)文件句柄(一种 3 参数形式的 open)来进一步改进您的代码,最重要的是,对所有 IO 操作进行错误检查,尤其是
open()
调用:或者,更好的是,不要在 IO 调用中硬编码文件名(以下做法可能会让您更快地找出问题):
As per Perl FAQ 5, you should be using forward slashes in your DOS/Windows filenames (or, as an alternative, escaping the backslashes).
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"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:Or, better yet, don't hard-code filenames in IO calls (the following practice MAY have let you figure out a problem sooner):
当不需要插值时,切勿使用插值字符串!您正在尝试从 \t 和 \n! 打开一个包含制表符和换行符的文件名!
当您不需要(或想要)插值时,请使用单引号。
新手 Perl 程序员似乎遇到的最大问题之一是他们不假思索地自动使用“”来表示所有内容。您需要了解“”和“”之间的区别,并且在键入之前始终需要思考,以便选择正确的选项。这是一个很难养成的习惯,但如果你想写出好的 Perl 语言,这一点就至关重要。
Never use interpolated strings when you don't need interpolation! You are trying to open a file name with a tab character and a newline character in it from the \t and the \n!
Use single quotes when you want don't need (or want) interpolation.
One of the biggest problems novice Perl programmers seem to run into is that they automatically use "" for everything without thinking. You need to understand the difference between "" and '' and you need to ALWAYS think before you type so that you choose the right one. It's a hard habit to get into, but it's vital if you're going to write good Perl.