Question

I have the following code for listing all files in a directory , I have trouble with path addressing ,my directory is is */tmp/* ,basically I want the files which are in a directory in tmp directory.but I am not allowed to use * ,do you have any idea?

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

closedir DIR;
Was it helpful?

Solution

opendir can't work with wildcards

For your task exists a bit ugly, but working solution

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
}

OTHER TIPS

Without globbing and * wildcard:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top