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.)


In reply to Re: grep beginning of string (updated) by haukex
in thread grep beginning of string by IB2017

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.