This subroutine accepts a list of numbers, and returns a list of hashrefs that look like: { $number => [ $idx1, $idx2, $idx_n, ... ] }, where each index represents where that particular number will be found in the original list.

use strict; use warnings; use Data::Dump 'dump'; my @numbers = ( 1, 2, 2, 4, 8, 42, 7, 2, 6, 7, 9, 42 ); my @duplicate_locations = find_duplicates( @numbers ); dump @duplicate_locations; sub find_duplicates { my @list = @_; my $idx; my %buckets; foreach my $item ( @list ) { push @{$buckets{$item}}, $idx++; } my @rv; foreach my $key ( keys %buckets ) { push @rv, { $list[$buckets{$key}->[0]] => $buckets{$key} } if @{$buckets{$key}} > 1; } return @rv; }

The output...

({ 42 => [5, 11] }, { 7 => [6, 9] }, { 2 => [1, 2, 7] })

Update:Simplifying the data structure returned simplifies the subroutine that produces it:

use strict; use warnings; use Data::Dump 'dump'; my @numbers = ( 1, 2, 2, 4, 8, 42, 7, 2, 6, 7, 9, 42 ); dump { find_duplicates( @numbers ) }; sub find_duplicates { my @list = @_; my $idx; my %buckets; foreach my $item ( @list ) { push @{$buckets{$item}}, $idx++; } delete @buckets{ grep { @{$buckets{$_}} < 2 } keys %buckets }; return %buckets; }

Now the output is...

{ 2 => [1, 2, 7], 7 => [6, 9], 42 => [5, 11] }

...so the actual return value from the sub is a hash where the keys are the values from your original list, and the values are array refs containing lists of where the corresponding elements are found. ...and we've stripped away any that weren't duplicated.


Dave


In reply to Re: list item comparison by davido
in thread list item comparison by robertw

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.