in reply to Multi @array searches

If you want to search two arrays and put the indices of the matching results from both into one array, you might need a way of keeping track of which array each stored index comes from (how do you know if this index corresponds to a match in @names, or in @desc, or in both?). Let's say you search @names first and @desc second, or you use OeufMayo's flattening approach: you might end up with the list (1,3,5,6,9,2,6,7). How do you know where the indices for @names leaves off and the indices of matching @desc entries begin? One answer is to return two lists (an array that consists of two anonymous arrays: the list of matches from @names, and the list of matches from @desc). Alternately, you could label which was which with a hash that consists of two anonymous arrays: so, with the above example, that hash would look like:

%matches = ( name=>[1, 3,5,6,9], desc=>[2,6,7] );
Either way, your search code wouldn't need to be modified much. Here's the hashy approach:
my %matches; $matches{name} = [ grep { $names[$_] =~/$pattern/ } 0 ..$#names ]; $matches{desc} = [ grep { $desc[$_] =~/$pattern/} 0.. $#desc];

And of course you would return \%matches instead of \@matches.

But it might be even simpler than this: if, as I suspect from your desire to remove duplicates, both arrays are part of a larger data structure (such that for each name, there is a corresponding description) then you can stick with the current approach, slightly modified. Simply change that grep line to grab the matches from either array:

my @matches = grep { $names[$_] =~ /$pattern/ || $desc[$_] =~/$pattern/ } 0 .. $#names;

which will also solve the problem of weeding out the duplicates.

HTH.

Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Replies are listed 'Best First'.
Re: Re: Multi @array searches
by akm2 (Scribe) on Mar 24, 2001 at 03:12 UTC
    my @matches = grep { $names[$_] =~ /$pattern/ || $desc[$_] =~/$pattern/ } 0 .. $#names;

    Shouldnt it read:

    my @matches = grep { $names[$_] =~ /$pattern/ || $desc[$_] =~/$pattern/ } 0 .. $#desc;

    If not, why not?

      Recall that 0 .. $#array; gives you a list of all the values between 0 and the maximum index of @array, or, in other words, the list of the indexes of @array.

      That bit of code assumes (and I made this assumption explicit) that the members of @names map 1:1 onto members of @desc; and if that is true, then

      0.. $#names
      and
      0 .. $#desc

      yield up the same list, so either is acceptable.

      HTH!

      Philosophy can be made out of anything. Or less -- Jerry A. Fodor