perl.org wrote:
From http://iis1.cps.unizar.es/Oreilly/perl/cookbook/ch04_07.htm, is this
really 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>




Reply via email to