user210757
user210757

Reputation: 7386

Perl Glob everything that doesn't end with zip

This is on windows - how do I glob, in perl, all files that don't end with ".zip"?

This is the current code, and for the purpose of this question, is not changeable - all that can be changed is the value of the $pattern variable.

my @arr = map { glob( $_ ) } $pattern;

As an aside question, what is the purpose of the map function in this code? It works, but I do not understand it.

Upvotes: 0

Views: 1844

Answers (2)

Joel Berger
Joel Berger

Reputation: 20280

The use of map here suggests that one might have multiple patterns to glob for. For example

my @arr = map { glob( $_ ) } ($pattern1, $pattern2);

which would make a list of all the files that match either pattern (possibly repeatedly). Note that you might also populate the array @arr using readdir builtin.

If you are stuck with the line mentioned, or if you use readdir, you may then filter out the results,

use File::Basename;
@arr = grep { ! (fileparse $_, '.zip')[2] } @arr;

To be even more rigorous you might want to filter out files which actually ARE zip files and not just ones with the name ending in .zip:

use File::MimeInfo::Magic;
@arr = grep { mimetype($_) ne 'application/zip' } @arr;

Upvotes: 5

jimtut
jimtut

Reputation: 2393

According to glob, it's more of a wildcard matching, not a true regex matching. I've never liked glob anyway (results are not repeatable within the same script, like if the glob is in a loop).

I know you said you couldn't change that glob line (so this might not be possible), but this code does what you're trying to do, using different code though:

opendir(DIR, ".") or die $!;
my @nonZipFiles = grep(!/^\.+|\.zip$/, readdir(DIR));
closedir(DIR);

print "$_\n" for @nonZipFiles;

Upvotes: 3

Related Questions