[Date Prev][Date Next][Thread Prev][Thread Next]
[Search]
[Date Index]
[Thread Index]
Re: [MacPerl-AnyPerl] an elegant uniquing
On Sat, Feb 05, 2000 at 10:35:48PM -0500, 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;
Unbalanced curly braces. I think that should be:
@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.
grep always returns $_ for each match; that's what it's for. grep selects
elements from the list that match the conditional expression.
> Is there a way to do this in one line?
What's so bad about two lines?
$seen{ ${$_}{names} }++ foreach @array_of_hashes;
@unqiue_names = keys %seen;
But here's one line:
@unique_names=map{!$seen{${$_}{names}}++?${$_}{names}:()}@array_of_hashes;
Ronald
==== Want to unsubscribe from this list?
==== Send mail with body "unsubscribe" to macperl-anyperl-request@macperl.org