Sorry, I didn't mean ordered as in sorted, I meant ordered as in I don't want to lose whatever order their in. But thanks for the tip.
Oops. There's been a lot of discussions on sorting lately, and I guess I mis-associated.
Anyway, my previous arguement still applies. You have to iterate over each element and determine if it has been seen before. The method you posted is as good as any. It does everything explicitly, so you can see what it's doing. On the other hand, I've always liked the grep method. I can't remember off-hand which is faster. They both perform exactly the same operations of iterating and comparing, but the grep method is a little less verbose.
On Fri, 02 Jul 2004 14:26:02 -0400, Randy W. Sims wrote
perl.org wrote:
From http://iis1.cps.unizar.es/Oreilly/perl/cookbook/ch04_07.htm, is thisreally the best way to ensure an *ordered* list contains only unique values? It seems like it could/should be easier. I wonder why the examples don't
use my.
%seen = (); @uniq = (); foreach $item (@list) { unless ($seen{$item}) { # if we get here, we have not seen it before $seen{$item} = 1; push(@uniq, $item); } } Faster
Well, in order to get a uniq list, you /must/ visit every element of the list. There are different ways to do this as demonstrated by the Cookbook. The only (wee tiny) optimization missed is an optimization that applies only to ordered lists: you only need to track the previous element in order to determine if the current item is unique. You don't need a hash.
The above becomes something like (untested):
my $prev = ''; my @uniq = (); foreach my $item (@list) { push(@uniq, $item) unless ($item eq $prev); $prev = $item; }
You can also use a 'for' loop and avoid variables all together by simply indexing into the array...
Randy.
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>