tags:

views:

346

answers:

7

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

+8  A: 

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";
}
magnifico
Rather similar answers - case-insensitive vs not, and parentheses vs not parentheses. :D
Jonathan Leffler
And we answered within one minute of each other. Great minds think alike 8D. Although in this case I guess I was the fastest gun in the west!
magnifico
Yeah - I should know better than to edit the question before giving an answer :D
Jonathan Leffler
+3  A: 

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.

Jonathan Leffler
+1  A: 
opendir (CURRDIR, $localdir);
@file_list = grep m/\.lt6$/, readdir CURRDIR;
closedir CURRDIR;
print STDOUT "Found Files: @file_list\n";
Hynek -Pichi- Vychodil
You don't need to check for . and .. if you only pass through things ending in .lt6. :)
brian d foy
A: 

And to add a little variety, you can also do stuff like this:

opendir(DIR, $path) || die qq([ERROR] Cannot opendir "$path" - $!\n);
my(@txt) = grep(m{\.txt$}, readdir DIR);
rewinddir DIR;
my(@lt6) = grep(m{\.lt6$}, readdir DIR);
rewinddir DIR;
my(@dirs) = grep(-d "$path/$_", readdir DIR);
closedir DIR;

And so on.

Joe Casadonte
+1  A: 

You can use File::Find::Rule;

use File::Find::Rule;

print "FOUND:\n    "
    , join( "\n    "
          , File::Find::Rule->file->name( '*.lt6' )->in( $path )
          )
    , "\n"
    ;
Axeman
This has the extra feature of recursive descent. If you only want the files in the top-level directory, this is a mighty big gun to pull out for no extra benefit.
brian d foy
It's only as heavy as the scope of the list of files, which is unspecified from the description. It avoids the procedural open-loop-close structure, and I've never liked the separate syntax for opendir/closedir, anyway. It hardly seemed an improvement over sh's $(ls).
Axeman
+2  A: 

my @file_list = glob "$localdir/*.lt6";

Jeff Hutton
A: 

Go to the command prompt

cd \

dir /s *.lt6 > mydir.txt