[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl-AnyPerl] an elegant uniquing



At 22.35 -0500 2000.02.05, Nathaniel Irons wrote:
>I've got an array full of anonymous hashes, each with 4-6 keys.  I would
>like to create a few arrays containing uniqued values from one of those
>keys, across all the hashes.
>
>This is a neat one-line trick I got from the Cookbook:
>
> @unique = grep { ! $seen{ $_ }++ } @not_unique;
>
>which I assumed I could adapt to my needs:
>
> @unique_names = grep { ! $seen{ ${$_}{names}++ } @array_of_hashes;
>
>which works, in that I get the right number of elements, but fails in
>that my new @u_names array is full of hash references, and not stringy
>hash values.  grep is returning "$_", not "${$_}{names}" as I intended.
>
>Is there a way to do this in one line?

The other suggestions are good, but mine is eviler, and eviler is gooder.

  @unique = grep { ! $seen{ $_->{names} }++ and $_ = $_->{names}, 1 } @loh;

That is, if it has not yet been seen, then $_ is set to the desired value
(so it may be returned) and 1 is returned from the block so the block
returns true (in case an element is undef, or 0, or '').  If the first part
fails, it will just return before $_ = $_->{names}, 1 is ever seen, because
the "and" short-circuits.

-- 
Chris Nandor          mailto:pudge@pobox.com         http://pudge.net/
%PGPKey = ('B76E72AD', [1024, '0824090B CE73CA10  1FF77F13 8180B6B6'])