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

is there a way I can search a two dimensional array to macth both the columns. I want to see if the combination of the two columns column1, column2 exists. I tried with this but did not work.
my @temp_exists = grep /$temp, $temp1/, @temp_array;
@temp_array is two dimensional.

Replies are listed 'Best First'.
Re: Two dimensional array
by shmem (Chancellor) on Oct 03, 2007 at 20:29 UTC
    @temp_array is two dimensional.
    How do you construct your array?

    If your array is an array of rows, each row containing two columns, it should be something like

    @array = ( [ 1, 2 ], [ 3, 4 ], [ 2, 5 ], );

    Now, if you want to find the row that contains the values 3, 4

    $temp = 3; $temp_1 = 4; @matching_rows = grep { $_->[0] == $temp && $_->[1] == $temp_1 } @arra +y;

    With the above @array the resulting array consists of one element, which is an anonymous array containing the values 3 and 4. See perlref and perlreftut for the [ ] constructor.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      I have the 2D array built from two arrays containg strings:
      @temp_array = (\@arry1, \@arry2); my @exists = grep { $_->[0] eq $temp1 && $_->[1] eq $temp2} @temp_a +rray ;
        Well, that changes things. Sticking to the row/column view, you have arrays of columns. Are those column arrays equal in element number?
        my @exists = grep { $temp_array[$_]->[0] eq $temp1 && $temp_array[$_]->[1] eq $temp2 } 0..$#{$temp_array[0]};

        The resulting @exists will contain the indexes into the two anonymous arrays your @temp_array holds where the comparison values are at the same index.

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Two dimensional array
by mwah (Hermit) on Oct 03, 2007 at 20:40 UTC
    Anonymousis there a way I can search a two dimensional array to macth both the columns?

    To match both column vectors in one stroke you have to introduce
    "another level of indirection", like:
    ... my @temp_array = ( [qw'a b'], [qw'c d'] ); my @temp1 = qw'a b'; my @temp2 = qw'c d'; my @temp_exists = map @$_, grep "@temp1" eq "@{$_->[0]}" && "@temp2" eq "@{$_- +>[1]}", \@temp_array ; print "@$_\n" for @temp_exists ...
    Regards

    mwa