Here's a rough draft (working properly, however) of one way to do it. I'm using a couple of hashes to reduce each array to simply a count of each element. Then the lesser of the two counts becomes the number of times set three should contain a given element.

use strict; use warnings; use List::Util qw/min/; my @list_a = qw/test test1 test2 test2 test/; my @list_b = qw/test1 test2 test2/; my( %element_count_a, %element_count_b ); %element_count_a = %{ count( \@list_a ) }; %element_count_b = %{ count( \@list_b ) }; foreach my $key ( keys %element_count_a ) { foreach ( 1 .. min( $element_count_a{$key}, exists( $element_count_b{$key} ) ? $element_count_b{$key} : '0' ) ) { print $key, "\n"; } } sub count { my( $list_aref ) = shift; my %element_count; foreach my $item ( @{ $list_aref } ) { $element_count{$item}++; } return \%element_count; }

Updated to choose better variable names.


Dave


In reply to Re: Compare Lists (Non Unique Intersection) by davido
in thread Compare Lists (Non Unique Intersection) by rsiedl

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.