Perl'-d'运算符未检测到目录

时间:2014-11-24 00:58:26

标签: perl

我将一些命令的输出传递给perl。输出包含一组文件名和目录,我希望perl过滤出目录。像这样:

...some commands... | perl -ne 'print $_ unless -d($_);'

问题是,它不是过滤目录!例如,输出类似于:

test/unit_test/ipc
test/unit_test/ipc/tc1.cpp

test/unit_test/ipc是一个目录,但仍然是输出。

1 个答案:

答案 0 :(得分:4)

由perl one-liner 读入的$_的值包括尾随换行符。因此,-d甚至找不到目录,更不用说识别它是一个目录。

这是一个解决方案:

...some commands... | perl -ne 'chomp $_; print "$_\n" unless -d $_ ;'

请注意使用chomp删除尾随换行符。


-n-p结合使用时,-l不仅会为print字符串添加换行符,而且chomp是输入。这意味着您的代码可以简化为

...some commands... | perl -nle 'print $_ unless -d $_;'

甚至

...some commands... | perl -nle'print if !-d'
相关问题