drmrgd has asked for the wisdom of the Perl Monks concerning the following question:
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:
This correctly prints the result: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"; } }
$ 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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Help understand why this grep does not work
by choroba (Cardinal) on Nov 02, 2013 at 15:42 UTC | |
|
Re: Help understand why this grep does not work
by LanX (Saint) on Nov 02, 2013 at 15:42 UTC | |
|
Re: Help understand why this grep does not work
by drmrgd (Beadle) on Nov 02, 2013 at 15:47 UTC | |
by LanX (Saint) on Nov 02, 2013 at 15:54 UTC | |
by drmrgd (Beadle) on Nov 02, 2013 at 16:15 UTC | |
by LanX (Saint) on Nov 02, 2013 at 16:21 UTC | |
by drmrgd (Beadle) on Nov 02, 2013 at 16:46 UTC | |
|