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

In reply to Re: Unique Array Items by davido
in thread Unique Array Items by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.