Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Monks Is there any way I can use grep to find out whether an element exist in a 2 dimensional array and if does exist get the rows from that array.

Comment on using grep with two dimensional arrays
Re: using grep with two dimensional arrays
by broquaint (Abbot) on Feb 18, 2003 at 18:17 UTC
    sub grep2d { my($ar, $el) = @_; grep { grep $el == $_, @$_ } @$ar; } use Data::Dumper; my $array = [ [ 1 .. 3 ], [ 4 .. 5 ], [ 3 .. 5 ] ]; print Dumper( grep2d($array, 3) ); __output__ $VAR1 = [ 1, 2, 3 ]; $VAR2 = [ 3, 4, 5 ];
    That should do the trick assuming you're using numbers, if you're using strings however you might want to use cmp or a regex match.
    HTH

    _________
    broquaint

      Nice one.. for completeness, here's a version that allows arbitrary tests:
      sub grep2d (&;@) { my $test = shift; grep { grep $test->(), @$_ } @_ } use Data::Dumper; my @array = ( [ 1 .. 3], [ 4 .. 5 ], [ 3 .. 5 ] ); print Dumper grep2d { $_ == 3 } @array;
      Note that this can likely be done more efficiently: the inner grep tests all elements, while we only care about whether or not one element matches. But unless the rows are very large, it probably doesn't matter.
Re: using grep with two dimensional arrays
by Limbic~Region (Chancellor) on Feb 18, 2003 at 18:21 UTC
    AFAIK - grep returns the number of matches in scalar context and the actual matches in list context - not the "row" at which it matched.

    For this, you will need to loop over your array - using both indices - something like the following untested code:

    #!/usr/bin/perl -w use strict; my @array = (); #actually use code that creates 2d array for ( my $i = 0; $i <= $#array; $i++) { for ( my $j = 0; $j <= $#{$array[$i]}; $j++ ) { if ($array[$i][$j] =~ /something/) { # Do something with $array[$i][$j] } } }

    Hope this helps point you in the right direction. I really like our Q/A section at PM, the http://www.perlfaq.com FAQ, and the http://www.perldoc.com FAQ.

    Cheers - L~R

    Update: Code now tested. As others have shown, if you do not need the indices and need only the row - other methods work with grep.

Re: using grep with two dimensional arrays
by Zaxo (Archbishop) on Feb 18, 2003 at 18:38 UTC
    my @two_d = ( [qw( foo bar baz)], [qw( bar baz quux)], [qw( baz quux foo)] ); my @rows = grep { grep {/foo/} @$_ } @two_d;

    You get a 2-d array containing only the rows matching 'foo'.

    After Compline,
    Zaxo