perl中的相对寻址,使用open dir

时间:2012-08-14 15:05:42

标签: perl opendir relative-addressing

我有以下代码列出目录中的所有文件,我遇到路径寻址问题,我的目录是 * / tmp / * ,基本上我想要在 tmp 目录中的目录中的文件。但是我不允许使用*,你有什么想法吗?

my $directory="*/tmp/*/";
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";
my @files = readdir DIR;
foreach $files (@files){
    #...
} ;

closedir DIR;

2 个答案:

答案 0 :(得分:2)

opendir无法使用通配符

对于你的任务存在有点难看,但工作解决方案

my @files = grep {-f} <*/tmp/*>; # this is equivalent of ls */tmp/* 
# grep {-f} will stat on each entry and filter folders
# So @files would contain only file names with relative path
foreach my $file (@files) {
    # do with $file whatever you want
}

答案 1 :(得分:1)

没有通配符和*通配符:

use 5.010;
use Path::Class::Rule qw();
for my $tmp_dir (Path::Class::Rule->new->dir->and(sub { return 'tmp' eq (shift->dir_list(1,1) // q{}) })->all) {
    say $_ for $tmp_dir->children;
}