in reply to Unique Array Items
@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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Unique Array Items
by graff (Chancellor) on Nov 07, 2003 at 04:17 UTC |