Igor
Igor

Reputation: 27250

How can I get all files in a directory, but not in subdirectories, in Perl?

How can I find all the files that match a certain criteria (-M, modification age in days) in a list of directories, but not in their subdirectories?

I wanted to use File::Find, but looks like it always goes to the subdirectories too.

Upvotes: 1

Views: 410

Answers (3)

William Pursell
William Pursell

Reputation: 212248

You can set File::Find::prune within the 'wanted' function to skip directory trees. Add something like $File::Find::prune = 1 if( -d && $File::Find::name ne ".");

Upvotes: -1

Ed Guiness
Ed Guiness

Reputation: 35247

@files = grep { -f && (-M) < 5 } <$_/*> for @folders;

Upvotes: 8

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

Use readdir or File::Slurp::read_dir in conjunction with grep.

 #!/usr/bin/perl

use strict;
use warnings;

use File::Slurp;
use File::Spec::Functions qw( canonpath catfile );

my @dirs = (@ENV{qw(HOME TEMP)});

for my $dir ( @dirs ) {
    print "'$dir'\n";
    my @files = grep { 2 > -M and -f }
                map { canonpath(catfile $dir, $_) } read_dir $dir;
    print "$_\n" for @files;
}

Upvotes: 2

Related Questions