Just playing around a bit with some text and grep and running into a problem I can't understand. Hoping one of you can enlighten me to what I'm overlooking.

Given two arrays with elements that consist of 3 space delimited characters, I want to print out any elements from array two for which the first two characters match an element from array 1. If I use grep in a scalar context, I can get it to work:

my @data1 = ( "a 1 a", "a 2 T", "a 3 C" ); my @data2 = ( "a 2 Y", "a 3 R", "a 4 Q", "b 5 R" ); for ( @data2 ) { my ($match) = $_ =~ /^(\w\s+\d)/; if ( grep { /$match/ } @data1 ) { print "$_\n"; } }
This correctly prints the result:
$ perl compare.pl a 2 Y a 3 R

However, if I try to use grep in a list context, storing the matches in '@result', I only get the second match and not the first:

my @results; for my $elem ( @data1 ) { my ($match) = $elem =~ /(\w\s+\d)/; @results = grep { /$match/ } @data2; } print "$_\n" for @results;
$ perl compare.pl a 3 R

What am I missing here? Why are both matches not being stored in @results?


In reply to Help understand why this grep does not work by drmrgd

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.