in reply to array comparison question

my %present; for my $a ( \@array1, \@array2, \@array3 ) { $present{ $_ }++ for @{ $ +a } } my @only_two = grep $present{ $_ } == 2, keys %present;

--
We're looking for people in ATL

Replies are listed 'Best First'.
Re^2: array comparison question
by jhourcle (Prior) on Aug 23, 2005 at 14:07 UTC

    If we go with the assumption that an element never occurs more than once in a single array, we don't need to track the arrays seperately, and can use Perl's array flattening:

    my %present; for my $a ( @array1, @array2, @array3 ) { $present{ $a }++ } my @only_two = grep $present{ $_ } == 2, keys %present;

    If we have to deal with multiples in any of the arrays:

    use List::MoreUtils qw(uniq); my %present = (); for my $a ( uniq(@array1), uniq(@array2), uniq(@array3) ) { $present{ +$a }++ } my @only_two = grep $present{ $_ } == 2, keys %present;
Re^2: array comparison question
by reasonablekeith (Deacon) on Aug 23, 2005 at 14:01 UTC
    This was my first thought too, it only works if you don't have the same value in any of the arrays more than once.
    my @array1 = (1,2,2); # 2 would be in the final array my @array2 = (1); my @array3 = (1);
    ---
    my name's not Keith, and I'm not reasonable.
      Modifying Fletch answer a little:
      my @array1 =( 1, 3, 6, 8); my @array2 =( 1, 2, 3, 4, 4); my @array3 =( 1, 2, 3, 5, 6); my %present; my @arrays = ( \@array1, \@array2, \@array3); for my $i ( 0 .. @arrays - 1) { $present{ $_ }{ $i } = 1 for @{ $arrays[ $i ] }; } my @only_two = grep { 2 == scalar keys %{$present{ $_ }} } keys %pre +sent; print "@only_two\n";

      OK, then how about removing duplicates before you check the arrays?