grep {/^$_.*/} @WORDS

Within the block of a grep, $_ is an alias for the current element of the list being inspected. So in your example, it'll be "trying", "helping" etc. A regular expression like /.../ without a target (as opposed to $string=~/.../) searches $_ by default, so with your regex, you're testing $_ against itself, which isn't what you want. (Also, while it's not wrong, /^$x.*/ can in this case be written more simply as /^$x/.)

$_ =~ m/^@WORDS/

Here, @WORDS is interpolated into the regular expression, so your regular expression actually becomes /^trying helping doing/. Also, here you'd be searching $_ for @WORDS, which is the wrong way around.

So your first approach with grep was good, the only mistake being with the $_ variable. Here's some code in which @result will contain only the element "helping":

my @WORDS = ("trying", "helping", "doing", "whelp"); my $SEARCH = "help"; my @result = grep {/^\Q$SEARCH\E/} @WORDS; print "$_\n" for @result;

(For the meaning of \Q...\E, see quotemeta.)


In reply to Re: Searching for a string within an array using regex by Anonymous Monk
in thread Searching for a string within an array using regex by Aquilae

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.