in reply to Simplest way to match/filter 2d array of values to search in perl

Thank you all for your comments. As an extension to this problem, I would also like to implement the following:

Count the number of occurences in the grep search where only those 'rows' are selected where the number of elements that exceed a particular value are defined. For eg, consider:
@arr = ( [ 'A' , 1, 0, 5, 6 ], [ 'B' , 3 , 4 , 5 , 6 ], [ 'C' , 2 , 4 ,3 ,5 ], [ 'D' , 6 , 7 , 8 ,8 ], [ 'E' , 2 , 5 , 4 , 5 ], [ 'F' , 4 , 8 , 8 ,8 ], [ 'G' , 1 , 2 , 4, 5 ], [ 'H' , 1 , 4 , 5, 6 ] );
Now, I define the number of string matches to be equal to '2' and threshold value to be '8'. The output should only include the rows where the no. of occurences of the value '8' is twice or more. i.e
__OUTPUT__ 'D' , 6 , 7 , 8 ,8 'F' , 4 , 8 , 8 ,8
Any idea on how to do this ?? Thank you very much !!!

Replies are listed 'Best First'.
Re^2: Simplest way to match/filter 2d array of values to search in perl
by AppleFritter (Vicar) on Jul 04, 2014 at 10:22 UTC

    Straightforward solution:

    my $matches = 2; my $threshold = 8; my @results = (); foreach my $row (@arr) { my $count; for (1..$#$row) { $count++ if($row->[$_] >= $threshold); } push @results, $row if($count >= $matches); } foreach(@results) { say join ",", @$_; }

    Shorter/idiomatic/obfuscated (take your pick) solution:

    my $matches = 2; my $threshold = 8; my @results = grep { $matches <= scalar grep { $_ >= $threshold } @$_[1..$#$_]; } @arr; foreach(@results) { say join ",", @$_; }

    Both of these output:

    D,6,7,8,8 F,4,8,8,8

    BTW, I'm assuming here that you're actually interested in whether there's at least $matches item equal to or greater than $threshold, since that's what "threshold" implies. If you're only interest in exactly that value, change >= $threshold to == $threshold in either code snippet above.