in reply to grep beginning of string
Works for me...
use warnings; use strict; use Data::Dumper; my $line = "X\tN"; my @tags = split /\t/, $line; my @Definition=("A", "NN", "B", "NNS", "YN", "ZX"); my @out = grep($_ =~ /^$tags[1]/, @Definition); print Dumper(\@out); __END__ $VAR1 = [ 'NN', 'NNS' ];
Could you show an SSCCE where it fails for you? Just an idea, you might want to check for stray whitespace in @tags (see Basic debugging checklist).
By the way, the match against $_ is implicit, and you probably want to use \Q...\E to have regex metacharacters match literally (see e.g. Mind the meta!). Also, I prefer the {BLOCK} form of grep - I would have written grep {/^\Q$tags[1]\E/} @Definition.
Minor ninja edits.
Update: If you instead mean that you want to check if $tags[1] begins with one of the strings in @Definition, then one way to do that is described in Building Regex Alternations Dynamically:
use warnings; use strict; use Data::Dumper; my @Definition=("NN", "NNS"); my ($defs) = map { qr/$_/ } join '|', map {quotemeta} sort { length $b <=> length $a } @Definition; for my $str ( "ABC", "NXY", "NNF", "NNSX" ) { print "$str: ", $str=~/^$defs/ ? "yes!\n" : "no\n"; } __END__ ABC: no NXY: no NNF: yes! NNSX: yes!
(Although ("NN", "NNS") is kind of redundant, ("NN") is enough.)
|
|---|