I'm attempting to solve a very simple problem - find strings in an array which only contain certain letters. However, I've run up against something in the behavior of regular expressions and/or grep
that I don't get.
#!/usr/bin/perl
use warnings;
use strict;
my @test_data = qw(ant bee cat dodo elephant frog giraffe horse);
# Words wanted include these letters only. Hardcoded for demonstration purposes
my @wanted_letters = qw/a c d i n o t/;
# Subtract those letters from the alphabet to find the letters to eliminate.
# Interpolate array into a negated bracketed character class, positive grep
# against a list of the lowercase alphabet: fine, gets befghjklmpqrsuvwxyz.
my @unwanted_letters = grep(/[^@wanted_letters]/, ('a' .. 'z'));
# The desired result can be simulated by hardcoding the unwanted letters into a
# bracketed character class then doing a negative grep: matches ant, cat, and dodo.
my @works = grep(!/[befghjklmpqrsuvwxyz]/, @test_data);
# Doing something similar but moving the negation into the bracketed character
# class fails and matches everything.
my @fails1 = grep(/[^befghjklmpqrsuvwxyz]/, @test_data);
# Doing the same thing that produced the array of unwanted letters also fails.
my @fails2 = grep(/[^@unwanted_letters]/, @test_data);
print join ' ', @works; print "\n";
print join ' ', @fails1; print "\n";
print join ' ', @fails2; print "\n";
Questions:
- Why does
@works
get the correct result but not@fails1
? Thegrep
docs suggest the former, and the negation section ofperlrecharclass
suggests the latter, although it uses=~
in its example. Is this something specifically to do with usinggrep
? - Why does
@fails2
not work? Is it something to do with array vs list context? It otherwise looks the same as the subtraction step. - Besides that, is there a pure regex way to achieve this that avoids the subtraction step?