检查 PATH 中是否存在文件
我有这样的东西:
if(! -e $filename) {
# do something
}
但我需要更改它,以便它甚至在我的路径上查找文件。有没有办法在不分析 PATH 的情况下实现这一目标?
I have something like this:
if(! -e $filename) {
# do something
}
but I need to alter it so that it looks for file even on my PATH. Is there any way to achieve this without analysing PATH?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
文件::Which
File::Which
如何在不查看
$ENV{PATH}
的情况下查看文件是否位于$ENV{PATH}
指定的目录之一中? ……这是一个反问句。这是我不久前编写的简短脚本。您应该能够根据您的需求进行调整:
How can you see if a file is in one of the directories specified in
$ENV{PATH}
without looking at$ENV{PATH}
? … That's a rhetorical question.Here is a short script I wrote some time ago. You should be able to adapt it for your needs:
系统在加载可执行文件时使用
PATH
变量。因此,为了让底层系统为您完成工作,我相信您需要尝试加载可执行文件。听起来这不是您想要做的。很可能有一些库可以提供此类功能,但编写自己的库非常简单。您只需要使用
split
然后迭代即可。The
PATH
variable is used by the system when loading executables. So to get the underlying system to do the work for you I believe you would need to attempt to load an executable. It doesn't sound like this is what you are looking to do.There may well be some library that will offer such functionality but it is very simple to write your own. You just need to use
split
and then iterate.补充 daxim 和 Sinan Ünür 的 有用的答案:
在有限情况下,如果您只关心是否给定的程序在系统路径中,您可以采取捷径:
如果目标程序是一个具有无副作用选项(除了生成标准输出)的 CLI,该选项会导致程序成功退出非常快 - 例如,
--version
- 您可以执行以下操作:To complement daxim's and Sinan Ünür's helpful answers:
In limited circumstances, if you only care whether or not a given program is in the system's path, you can take a shortcut:
If the target program is a CLI that has a side-effect-free option (other than producing stdout output) that causes the program to exit successfully very quickly - e.g.,
--version
- you can do the following:如果你想使用核心模块,有
can_run()
来自 IPC::Cmd。File::Which 的 perldoc 指出了一个警告,即这也将搜索当前目录,即使那不在你的路径中:
If you want to use a core module, there's
can_run()
from IPC::Cmd.The perldoc for File::Which points out the caveat that this will also search the current directory, even if that's not in your path: