in reply to Unique Array Items

Ok, here's my solution. Instead of grep, it uses map to generate an anonymous hash, which is fed into keys, which is fed into sort....
@array = sort { $a <=> $b } keys %{ { map { $_ => 0 } @array } };

To me it's a pretty clear and readable solution, but others seem to prefer the grep alternatives. To each his own... that ought to be another Perl motto. ;)


Update: Here is a comparison of several of the methods layed out in this thread. My map method isn't the fastest, but I'll defend it on clarity...

use strict; use warnings; use Benchmark; my @testdata; push @testdata, int rand (100) for 1..500; sub map_test { my @array = @{[ @testdata ]}; @array = sort { $a <=> $b } keys %{ { map { $_ => 0 } @array } }; 1; } sub grep_test { my %h; my @array = @{[ @testdata ]}; @array = sort {$a <=> $b} grep { ! $h{$_}++ } @array; 1; } sub do_test { my %h; my @array = @{[ @testdata ]}; @array = do { my %h; @h{ @array } = (); sort keys %h }; 1; } my $count = 1000; timethese ( $count, { 'Map' => \&map_test, 'Grep' => \&grep_test, 'Do' => \&do_test } );

And the output:

Benchmark: timing 1000 iterations of Do, Grep, Map... Do: 8 wallclock secs ( 7.90 usr + 0.00 sys = 7.90 CPU) @ 126.58/s + (n=1000) Grep: 9 wallclock secs ( 8.74 usr + 0.00 sys = 8.74 CPU) @ 114.42 +/s (n=1000) Map: 11 wallclock secs (11.26 usr + 0.00 sys = 11.26 CPU) @ 88.81/s + (n=1000)



Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: Unique Array Items
by graff (Chancellor) on Nov 07, 2003 at 04:17 UTC
    You might try benchmarking the "do_map" case with:
    ... keys %{ map { $_ => undef } @array }; # not 0
    I actually don't know how it would compare in terms of speed, but it would use a fair bit less memory. (I just checked the process size of "=> 0" vs. "=> undef", and the latter was about 1 MB smaller on a set of 100K hash keys.)