Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Most elegant way to dispose of duplicates using map

by davorg (Chancellor)
on Oct 30, 2006 at 16:26 UTC ( [id://581330]=note: print w/replies, xml ) Need Help??


in reply to Most elegant way to dispose of duplicates using map

The FAQ How can I remove duplicate elements from a list or array? can be adapted for use here.

my %seen; @partTuples = grep { ! $seen{$_->{id}}++ } @partTuples;
--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Most elegant way to dispose of duplicates using map
by rashley (Scribe) on Oct 30, 2006 at 16:33 UTC
    Perfect, this is exactly what I was looking for. Thanks!
      Just for the sake of intelectual growth, how could one tweak this to eliminate duplicates of id/versions pairs, instead of just id?
        You just need to make a key for the %seen hash that is your id and version joined together in some way. Here I join them with a colon

        use strict; use warnings; use Data::Dumper; my @partTuples = ( q{abc,1.1,apple}, # 1st element q{def,3.6,orange}, # no dups. so OK q{abc,1.5,pear}, # OK id only dup. q{abc,1.1,kiwi}, # dup. id and version q{ghi,1.2,peach}, # no dups. so OK q{xyz,1.1,plum}, # OK version only dup. ); my %seen = (); my @uniquePTs = grep {! $seen{join q{:}, $_->{id}, $_->{version}} ++} map { { id => $_->[0], version => $_->[1], classification => $_->[2] } } map { [split m{,}] } @partTuples; print Dumper(\@uniquePTs);

        The output is

        $VAR1 = [ { 'version' => '1.1', 'classification' => 'apple', 'id' => 'abc' }, { 'version' => '3.6', 'classification' => 'orange', 'id' => 'def' }, { 'version' => '1.5', 'classification' => 'pear', 'id' => 'abc' }, { 'version' => '1.2', 'classification' => 'peach', 'id' => 'ghi' }, { 'version' => '1.1', 'classification' => 'plum', 'id' => 'xyz' } ];

        Cheers,

        JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://581330]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2024-04-25 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found