Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter filenames based on their extension?

Tags:

list

filter

perl

The following script stores all the files and directories in the array @file_list.

How do I only filter only files with the .lt6 extension and none other than that?

opendir (CURRDIR, $localdir);
@file_list = grep !/^\.\.?$/, readdir CURRDIR;
print STDOUT "Found Files: @file_list\n";

cheers

like image 411
Neel Avatar asked Dec 06 '22 07:12

Neel


2 Answers

Try this:

grep(/\.lt6$/i, readdir(CURRDIR))

I've used it many times. It works, although now I prefer to use File::Next for this sort of thing.

Example:

use File::Next;

my $iter = File::Next::files( { file_filter => sub { /\.lt6$/ } }, $localdir )

while ( defined ( my $file = $iter->() ) ) {
    print $file, "\n";
}
like image 69
Jim Counts Avatar answered Dec 28 '22 07:12

Jim Counts


Don't forget to closedir().

Your grep should look for:

my(@file_list) = grep /\.lt6$/, readdir CURRDIR;

Assuming the rest of your syntax is approximately correct.

like image 30
Jonathan Leffler Avatar answered Dec 28 '22 07:12

Jonathan Leffler