ParoX
ParoX

Reputation: 5933

How do I filter filenames with regex instead of glob expressions?

I am filtering files of a directory:

chdir '/home/brian/mypics/';
@picArray   = <*.JPG *.GIF *.jpg *.gif *.PNG *.png *.jpeg>;
@soundArray = <*.mid *.MID *.wav *.WAV *.mp3 *.MP3 *.wma *.WMA *.ogg *.OGG>;

I know there has to be a better and easier way, something that's case-insensitive and can allow for regex like gif|png|jpe?g and wma|ogg|mp3|wave?|midi?.

How can I have an array to catch all unknown file types (such if one was .exe, it would be in an array all of it's own as the other two never caught it)?

Upvotes: 0

Views: 214

Answers (1)

bigendian
bigendian

Reputation: 818

opendir/readdir would work:

opendir(my $dh, "/tmp/");
my @files = readdir($dh);
my @picArray = grep { /\.(gif|png|jpe?g)$/i } @files;
my @soundArray = grep { /\.(wma|ogg|mp3|wave?|midi?)$/i } @files;

Upvotes: 2

Related Questions