in reply to Adding Unique Elements to Array

There are several ways to do this and quite a few nodes out there that point to answers.

my @list = qw( ... ); my %hash; undef @hash{@list}; print $_, "\n" for keys %hash;


or

my @list = qw( ... ); my %hash; grep { $hash{$_}++ } @list; print $_, "\n" foreach keys %hash;
--------------
It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs

Replies are listed 'Best First'.
Re^2: Adding Unique Elements to Array
by Roy Johnson (Monsignor) on Feb 28, 2005 at 19:50 UTC
    While both of these work, neither is very good code. In the first example, you pass undef an array slice, but undef doesn't work on array slices (you're just not using undef for its designed purpose, so you don't care). It would be better to say
    @hash{@list} = ();
    In the second, you use grep where a foreach is more sensible. In fact,
    1 for @hash{@list};
    works just as well (you don't even have to assign anything).

    Caution: Contents may have been coded under pressure.
        I'm not sure whether you're making your case based on cargo cultism or micro-optimization; neither is a good idea. Abusing undef benchmarks at about 20% faster than assigning empty list, but it relies on undocumented behavior.

        You can get within 2% by saying

        @hash{@list} x= 0;
        which is still odd (and gives a warning for using uninitialized values), but is at least documented, if your code is bottlenecking at your key-creation section. In the absence of a bottleneck, it is better to write clear code than marginally faster code.

        Caution: Contents may have been coded under pressure.