in reply to Remove redundency from an array

Use a hash.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @array = (1,1,3,3,2,3,5,7,5,2); my %h; $h{$_}++ for @array; @array = keys %h; print Dumper \@array;

Replies are listed 'Best First'.
Re^2: Remove redundency from an array
by jdporter (Paladin) on Sep 24, 2007 at 12:45 UTC
    $h{$_}++ for @array;

    That works, but is rather inefficient. Much better is to assign to a hash slice:

    @h{@array} = ( );
    A word spoken in Mind will reach its own level, in the objective world, by its own weight
      Bruce and jd's solution are both fine and far less ugly than the FAQ. Is there a reason these solutions aren't on there and the FAQ version is using splice?

        The first code block in the FAQ says:

        my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array );
        The first comment is my solution and the second is essentially the same as bruceb3's. Actually, I don't see where the FAQ suggests using splice for this.

        Do you mean the Answer: page, rather than the FAQ? If so, take another look at the text preceding the code... "The answers in the FAQ don't modify the array in-place. In case that's what you need, you can do the following: The splice is needed to modify the original array in-place.