9.6. Globbing, or Getting a List of Filenames Matching a PatternProblem
You want to get a list of filenames similar to MS-DOS's Solution
Perl provides globbing with the semantics of the Unix C shell through the @list = <*.c>; @list = glob("*.c");
You can also use opendir(DIR, $path); @files = grep { /\.c$/ } readdir(DIR); closedir(DIR); The CPAN module File::KGlob does globbing without length limits: use File::KGlob; @files = glob("*.c"); Discussion
Perl's built-in
To get around this, you can either roll your own selection mechanism using the built-in
At its simplest, an @files = grep { /\.[ch]$/i } readdir(DH); You could also do this with the DirHandle module: use DirHandle; $dh = DirHandle->new($path) or die "Can't open $path : $!\n"; @files = grep { /\.[ch]$/i } $dh->read(); As always, the filenames returned don't include the directory. When you use the filename, you'll need to prepend the directory name: opendir(DH, $dir) or die "Couldn't open $dir for reading: $!"; @files = (); while( defined ($file = readdir(DH)) ) { next unless /\.[ch]$/i; my $filename = "$dir/$file"; push(@files, $filename) if -T $file; }
The following example combines directory reading and filtering with the Schwartzian Transform from
Chapter 4,
Arrays
, for efficiency. It sets @dirs = map { $_->[1] } # extract pathnames sort { $a->[0] <=> $b->[0] } # sort names numeric grep { -d $_->[1] } # path is a dir map { [ $_, "$path/$_" ] } # form (name, path) grep { /^\d+$/ } # just numerics readdir(DIR); # all files
Recipe 4.15
explains how to read these strange-looking constructs. As always, formatting and documenting your code can make it much easier to read and See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|