in reply to Adding regex filters from command-line options

Use a closure which captures the pattern.

my @filters = ( ( map { my $re = $_; sub { $_[0] =~ $re } } @accept ), ( map { my $re = $_; sub { $_[0] !~ $re } } @reject ), );

You could even pre-compile the patterns.

my @filters = ( ( map { my $re = qr/$_/; sub { $_[0] =~ $re } } @accept ), ( map { my $re = qr/$_/; sub { $_[0] !~ $re } } @reject ), );

I suspect that building a single pattern would be faster, though.

my $filter; if ( @accept || @reject ) { $filter = join "", ( map "(?=(?s:.*?)$_)", @accept ), ( map "(?!(?s:.*?)$_)", @reject ); $filter = qr/^$filter/; } else { $filter = qr/(*FAIL)/; } sub filter { map $_->[0], grep { $_->[1] =~ $filter } @_ }

Replies are listed 'Best First'.
Re^2: Adding regex filters from command-line options
by Anonymous Monk on Mar 17, 2025 at 20:20 UTC
    Nice! But note the first two solutions require an extra set of enclosing parenthesis or the @reject filters will silently not be applied.

      woops! Fixed.