> -----Original Message-----
> From: Jennifer Pan [mailto:[EMAIL PROTECTED]]
> Sent: Friday, August 10, 2001 10:20 AM
> To: [EMAIL PROTECTED]
> Subject: grep repetitive elements?
>
>
> 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;
> }
Well, grep returns a list of matches. Using a list in scalar context gives
the number of elements in the list, so this should work:
for $L1 (@list1) {
print $L1 if (grep { $_ eq $L1 } @list2) > 2;
}
But this is pretty inefficient unless @list2 is small. Might be
better to count stuff in a hash:
%temp = map { $_ => 0 } @list1;
for (@list2) {
$temp{$_}++ if exists $temp{$_};
}
print "$_\n" for grep { $temp{$_} > 2 } @list1;
(Normally I would use keys(%temp) instead of @list1 on the last line,
but this has the advantage of preserving the original order of elements
in @list1 if that is important.)
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]