我有这个来自 Perl Cookbook 的简单代码递归打印所有目录和文件:
use File::Find;
@ARGV = qw(.) unless @ARGV;
find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;
我不懂print $File::Find::name, -d
的语法。这要怎么解释?如果 -d
测试 $File::Find::name
是否是目录,因此 -d
是函数 print 的参数
?或者 Perl 是否明确地将 standalone -d
解释为 if -d
?
最佳答案
不,-d
是一个独立的语句,它测试 $_
。所以本质上是一样的
-d $_ && '/'
上面写着“如果文件是一个目录,则返回一个斜杠字符(打印)”。 sub
代码块由 File::Find
中的 find
函数使用,其中 $_
包含当前文件的文件名。
逗号 ,
分隔为 print
语句返回字符串的语句列表:
print $File::Find::name, # print the files name
-d && '/', # if it is a dir, print /
"\n" # print a newline
在 documentation对于 -d
(包含在 perldoc for -X
中,其中列出了所有文件测试)状态:
If the argument is omitted, tests $_ ...
这适用于 -X
下的所有文件测试。
&&
可以这样使用的原因是它比逗号运算符 ,
具有更高的优先级。这记录在 perldoc perlop
关于Perl:无条件的文件测试运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68743839/