Two paths. See index, also quotemeta for \Q \E interpolation modifiers. (Update: Note that, of course, this approach will not work if the sub-string being searched for is longer than the target string; e.g., 'helper' will not match to anything in the @WORDS example array below.)
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @WORDS = qw(trying helping doing do xdo help hel xhelp); my $s = 'help'; ;; my @hits = grep m{ \A \Q$s\E }xms, @WORDS; dd \@hits; ;; $s = 'do'; @hits = grep index($_, $s) == 0, @WORDS; dd \@hits; ;; dd \@WORDS; " ["helping", "help"] ["doing", "do"] ["trying", "helping", "doing", "do", "xdo", "help", "hel", "xhelp"]
Update: If the strings being compared can be of any length relative to each other, here's a way to find strings that are identical at their beginnings. (This can easily be changed to find strings identical at their ends by throwing in a couple of reverse function calls.)
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @words = qw(he xhelper hello hel help helper helping); my $t = 'helper'; ;; my @hits = grep overlap($_, $t, 3), @words; dd \@hits; ;; @hits = grep overlap($_, $t, 4), @words; dd \@hits; ;; @hits = grep overlap($_, $t, 6), @words; dd \@hits; ;; @hits = grep overlap($_, $t, 7), @words; dd \@hits; ;; sub overlap { my ($s, $t, $min) = @_; ;; return ($s ^ $t) =~ m{ \A \x00{$min,} }xms; } " ["hello", "hel", "help", "helper", "helping"] ["help", "helper", "helping"] ["helper"] []
In reply to Re: Searching for a string within an array using regex
by AnomalousMonk
in thread Searching for a string within an array using regex
by Aquilae
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |