判断目录中是否存在文件的最佳方法是什么?
我正在尝试移动文件,但我想在这样做之前确保它存在。在 Perl 中执行此操作的最简单方法是什么?
我的代码是这样的。我查找了 open
命令,但我不确定这是否是最简单的方法。
if #Parser.exe exist in directory of Debug
{
move ("bin/Debug/Parser.exe","Parser.exe");
}
elsif #Parser.exe exist in directory of Release
{
move ("bin/Release/Parser.exe","Parser.exe");
}
else
{
die "Can't find the Parser.exe.";
}
谢谢。
I'm trying to move a file but I want to ensure that it exists before I do so. What's the simplest way to do this in Perl?
My code is like this. I looked up the open
command, but I am not sure it is the simplest way or not.
if #Parser.exe exist in directory of Debug
{
move ("bin/Debug/Parser.exe","Parser.exe");
}
elsif #Parser.exe exist in directory of Release
{
move ("bin/Release/Parser.exe","Parser.exe");
}
else
{
die "Can't find the Parser.exe.";
}
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要的是 文件测试运算符检查文件是否存在。具体来说,您需要
-e
运算符来检查文件 e 是否存在。What you need is a file test operator to check if the file exists. Specifically, you need the
-e
operator which checks if a file exists.您可以使用
-e
file test 来检查文件是否存在:You can make use of
-e
file test to check for file existence:就我个人而言,我不喜欢这些解决方案中文件/路径名的重复 - 就我自己而言,我怀疑我可能会意外地将其更改为
我会做类似的事情
,或者如果这有点危险
Personally I don't like the duplication of the file/ path name in these solutions - speaking for myself I suspect I might change accidently it to
I would do something like
Or if that is a bit risque
当 Justintime 注意到重复并试图消除它时,他就走上了正确的道路。我在最小化方面比他更进一步。
不过,通过封装列表迭代来删除所有重复项是有意义的,而不是仅封装代码的复制/移动部分。
我将子例程放入模块中,以便以后可以根据需要重用。这也减少了重复代码。
在SearchMove.pm
包中SearchMove;
使用严格;
使用警告;
现在您可以在许多不同的项目中使用
search_and_move
。justintime is on the right track when he notes the repetition and seeks to eliminate it. I took the minimization a step farther than he did.
Rather than encapsulate only the copy/move portion of the code, though, it makes sense to remove as all the repetition by encapsulating the list iteration.
I put the subroutine in a module so it can be reused later as needed. This also reduces repeated code.
In SearchMove.pm
package SearchMove;
use strict;
use warnings;
Now you can use
search_and_move
in many different projects.