On Aug 10, Jennifer Pan said:

>I have two list, 
>@list1 and @list2, each element @list1 is unique (could be a hash I
>suppose)
>
>I want to find out all the elements @list2 that is an element in list1
>and have appeared two or more times
>
>I want to use GREP but I don't know how to grep certain element only
>when it happens >2 times, or is it possible?
>
>foreach $L1 (@list1) {
>       if ( grep /$L1/ @list2 more than twice?) {
>       print $L1;
>}

grep() returns the elements that passed in list context, and the NUMBER of
elements that passed in scalar context.

  for $element (@list1) {
    if (grep($_ eq $element, @list2) > 1) { print $element }
  }

But I don't like the looks of that, really.  We're going through the array
a lot.

I'd do something like:

  my %freq;
  $freq{$_}++ for @list2;  # create a hash of key -> frequency

  for (@list1) {
    print $freq{$_} if $freq{$_} > 1;
  }

This only loops through each array once.  Your way loops through @list2
many times.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to