in reply to Can't remove the the duplicate element when it's the last one in the array

Take a look at the  uniq() function ...

I second that.

Your code seems to be too "tricky" ...

Too tricky by half. But if you are going to recommend 'simple' code, at least recommend the idiomatic version:

>perl -wMstrict -le "my @ra = (1, 3, 2, 3, 2, 3, qw{X b X c X}); my %seen; @ra = grep !$seen{$_}++, @ra; print qq{@ra}; " 1 3 2 X b c

Replies are listed 'Best First'.
Re^2: Can't remove the the duplicate element when it's the last one in the array
by johngg (Canon) on Dec 18, 2009 at 19:32 UTC

    If order need not be preserved I think a hash slice is quicker.

    $ perl -MBenchmark=cmpthese -Mstrict -wE ' > my @arr; > push @arr, int rand 20 for 1 .. 1000; > cmpthese( > -5, > { > grep => sub > { > my %seen; > my @uniq = grep ! $seen{ $_ } ++, @arr; > }, > slice => sub > { > my %seen; > @seen{ @arr } = ( 1 ) x @arr; > my @uniq = keys %seen; > }, > } > );' Rate grep slice grep 3041/s -- -29% slice 4260/s 40% -- $

    However, take my benchmarks with a pinch of salt, I often make a complete dog's breakfast of them :-(

    I hope this is of interest.

    Cheers,

    JohnGG

      johngg, it looks interesting and helpful, I will have a try:)
Re^2: Can't remove the the duplicate element when it's the last one in the array
by littlehorse (Sexton) on Dec 20, 2009 at 07:43 UTC
    AnomalousMonk, your example are very helpful to me, thanks a lot!