uniq

Ludek Finstrle luf na gvid.cz
Čtvrtek Listopad 28 13:25:22 MET 2002


> mam pole @list a chtel bych z nej vybrat pouze unikatni polozky. Napsal
> jsem
> 
> 
>     use strict;
> 
>     my %uniq = map { $_ => 1 } @list;
>     @list = keys %uniq;
> 
> 
> a pak jsem stravil hodne casu tim, ze jsem se to pokousel napsat to do
> jednoho prikazu. Pomuze nekdo?

Neodpovim vam primo, ale v man perlfaq4 se pise:

       How can I remove duplicate elements from a list or array?

       There are several possible ways, depending on whether the
       array is ordered and whether you wish to preserve the
       ordering.

       a) If @in is sorted, and you want @out to be sorted: (this
       assumes all true values in the array)
               $prev = 'nonesuch';
               @out = grep($_ ne $prev && ($prev = $_), @in);

           This is nice in that it doesn't use much extra memory,
           simulating uniq(1)'s behavior of removing only adja-
           cent duplicates.  It's less nice in that it won't work
           with false values like undef, 0, or ""; "0 but true"
           is OK, though.

       b) If you don't know whether @in is sorted:
               undef %saw;
               @out = grep(!$saw{$_}++, @in);

       c) Like (b), but @in contains only small integers:
               @out = grep(!$saw[$_]++, @in);

       d) A way to do (b) without any loops or greps:
               undef %saw;
               @saw{@in} = ();
               @out = sort keys %saw;  # remove sort if undesired

       e) Like (d), but @in contains only small positive inte-
       gers:
               undef @ary;
               @ary[@in] = @in;
               @out = grep {defined} @ary;

       But perhaps you should have been using a hash all along,
       eh?

Takze podle bodu d) predpokladam, ze to asi na jeden radek rozumne nejde.
Ale mozna se pletu ;o) Ale me se vice libi reseni b) ...

Luf


Další informace o konferenci Perl