0

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;
shaq
  • 799
  • 1
  • 7
  • 12

2 Answers2

2

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
}
CyberDem0n
  • 14,545
  • 1
  • 34
  • 24
  • 1
    I usually use `glob "*/tmp/*"` rather than `<*/tmp/*>` as I find it confuses other Perl guys less often (long-time Perl-ers often seem to forget what that syntax does). – zostay Aug 14 '12 at 16:49
  • Even Perl itself is sometimes confused whether `<>` means [`glob`](http://p3rl.org/glob) or [`readline`](http://p3rl.org/readline). In my book, it is good style to always spell it out. – daxim Aug 14 '12 at 17:10
1

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;
}
daxim
  • 39,270
  • 4
  • 65
  • 132
  • 1
    Neither did I, now I do. Great module. @daxim dir_list returns undefined on empty dir, I used (shift->dir_list(1,1) // '') – Bill Ruppert Aug 14 '12 at 17:11