This method will allow records to appear in any order, meaning that "Peter white" and "Peter brown" don't necessarily have to appear grouped together in the original data set. That's the pro to the following solution. The con is that there is no effort made to preserve the original order (just as no assumptions are made that the original set came in any particular order in the first place). It would be trivial to sort alphabetically though, or even to keep track of original order if necessary.

A hash of arrays is used, and color values are pushed into arrays keyed off of the name field. Here's the code:

use strict; use warnings; my %sets; while( <DATA> ) { chomp; next unless length; my( $entry, $color ) = split /\s+/; push @{$sets{$entry}}, $color; } foreach my $entry ( keys %sets ) { print $entry; foreach my $color ( @{$sets{$entry}} ) { print "\t$color\n"; } } __DATA__ John red Mike yellow Peter white Peter brown Jim purple Antony orange Antony green George black

Dave


In reply to Re: combine duplicate entries by davido
in thread combine duplicate entries 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.