【问题标题】:Perl: file test operator without conditionPerl:无条件的文件测试运算符
【发布时间】:2021-08-11 14:22:10
【问题描述】:

我有这个来自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 是否明确地将 独立 -d 解释为 if -d

【问题讨论】:

    标签: perl testing operators


    【解决方案1】:

    不,-d 是一个独立的语句,它测试$_。所以本质上是一样的

    -d $_ && '/'
    

    上面写着“如果文件是一个目录,则返回一个斜杠字符(打印)”。 sub 代码块由来自File::Findfind 函数使用,其中$_ 包含当前文件的文件名。

    逗号, 分隔为print 语句返回字符串的语句列表:

    print $File::Find::name,   # print the files name
    -d && '/',                 # if it is a dir, print /
    "\n"                       # print a newline
    

    -ddocumentation 中(包含在列出所有文件测试的-X 的perldoc 中)状态:

    If the argument is omitted, tests $_ ...
    

    这适用于-X 下的所有文件测试。

    && 可以这样使用的原因是它比逗号运算符, 具有更高的优先级。这记录在perldoc perlop

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 2023-04-10
      • 2016-01-22
      • 2012-05-05
      • 2010-12-16
      • 2021-08-26
      • 2022-01-02
      • 2017-12-03
      • 2013-03-22
      相关资源
      最近更新 更多