in reply to using grep with two dimensional arrays

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

Replies are listed 'Best First'.
Re: Re: using grep with two dimensional arrays
by xmath (Hermit) on Feb 18, 2003 at 18:48 UTC
    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.