如何获取 Perl 中的目录列表?
我想在 Perl 程序中执行 ls
作为 CGI 脚本的一部分。 为此,我使用了 exec(ls),但这不会从 exec 调用中返回。
有没有更好的方法来获取 Perl 中的目录列表?
I would like to execute ls
in a Perl program as part of a CGI script. For this I used exec(ls)
, but this does not return from the exec
call.
Is there a better way to get a listing of a directory in Perl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
Exec根本没有返回。 如果你想要这样,请使用系统。
如果你只想读取一个目录,open/read/close-dir可能更合适。
Exec doesn't return at all. If you wanted that, use system.
If you just want to read a directory, open/read/close-dir may be more appropriate.
其他人似乎都陷入了问题的 exec 部分。
如果您想要目录列表,请使用 Perl 的内置
glob
或opendir
。 您不需要单独的过程。Everyone else seems stuck on the
exec
portion of the question.If you want a directory listing, use Perl's built-in
glob
oropendir
. You don't need a separate process.exec 不会将控制权交还给 perl 程序。
system 会,但它不会返回 ls 的结果,而是返回一个状态代码。
刻度线``将为您提供我们命令的输出,但有些人认为这是不安全的。
使用内置的 dir 函数。
opendir、readdir 等。
http://perldoc.perl.org/functions/opendir.html
http://perldoc.perl.org/functions/readdir.html
exec does not give control back to the perl program.
system will, but it does not return the results of an ls, it returns a status code.
tick marks `` will give you the output of our command, but is considered by some as unsafe.
Use the built in dir functions.
opendir, readdir, and so on.
http://perldoc.perl.org/functions/opendir.html
http://perldoc.perl.org/functions/readdir.html
为了获得系统命令的输出,您需要使用反引号。
然而,Perl 本身擅长处理目录。 我建议使用 File::Find::Rule。
In order to get the output of a system command you need to use backticks.
However, Perl is good in dealing with directories for itself. I'd recommend using File::Find::Rule.
还有一个例子:
Yet another example:
使用 Perl 通配符:
Use Perl Globbing:
编辑:哎呀! 我以为你只是想要一个目录列表...删除“目录”调用以使该脚本执行您想要的操作...
在我看来,使用文件句柄是错误的方法。 下面是使用File::Find::Rule查找指定目录下的所有目录的示例。 对于你正在做的事情来说,这似乎有些过头了,但后来这可能是值得的。
首先,我的一行解决方案:
现在是一个带有注释的更冗长的版本。 如果您安装了 File::Find::Rule,您应该能够毫无问题地运行它。 不要害怕 CPAN。
EDIT: Whoops! I thought you just wanted a listing of the directories... remove the 'directory' call to make this script do what you want it to...
Playing with filehandles is the wrong way to go in my opinion. The following is an example of using File::Find::Rule to find all the directories in a specified directory. It may seem like over kill for what you're doing, but later down the line it may be worth it.
First, my one line solution:
Now a more drawn out version with comments. If you have File::Find::Rule installed you should be able to run this no problem. Don't fear the CPAN.
我建议您查看 IPC::Open3。 与系统或反引号相比,它允许对生成的进程进行更多的控制。
I would recommend you have a look at IPC::Open3. It allows for far more control over the spawned process than system or the backticks do.
在 Linux 上,我更喜欢找到:
On Linux, I prefer find: