user3425900 user3425900 - 7 months ago 25
Perl Question

Perl Grep Exclusion

I'm grepping values for a list of legitimate file names but there are certain file name matches I'm trying to exclude. I can't quite figure out the exclusions.

List = (
"fileA",
"Makefile.am.cppcheck",
"Makefile.am.cpplint",
"README-autotools.md",
"README-metrics.md",
"README.md",
"autogen.sh",
"configure.ac",
"test.pl",
)

@files = grep(/(?!readme|makefile)([a-z]\.[a-z])/i,@list);


The grep works fine without the exclusion but what am I missing to exclude items matching (readme|makefile) or other patterns?

EDIT: My filenames must include a period (such as test.pl), hence the reason for exclusions as opposed to weeding out the unwanted names alone.

Answer

It's the "magic regex" again, that's expected to move the earth in a single pattern

It's hard to tell from your question what result you want, but it looks like you want any file that has a dot in its name that doesn't start with readme or makefile

So just write that. After all, that's how .gitignore works: it's just a list of files or file patterns to ignore, it's not one long super-complicated glob expression

This way others, and you yourself in six months' time, will be able to make out what your code does

use strict;
use warnings qw/ all FATAL /;
use feature 'say';

my @list = qw/
    fileA  
    Makefile.am.cppcheck  
    Makefile.am.cpplint  
    README-autotools.md  
    README-metrics.md  
    README.md  
    autogen.sh  
    configure.ac  
    test.pl  
/;

my @filtered = grep {
    /\./ and not /^readme/i and not /^makefile/i;
} @list;

say for @filtered;

output

autogen.sh
configure.ac
test.pl