Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello There are two arrays that have strings. How can i compare them and get as result the number of strings that occur in both? Also, if for example there are two strings in one array the same and the same string is in the other array i only want 1 to be added. SO, unless there are two of the same string in each array (and add 2) then don't bother with the second one.

I have written some code but it doesn't work. Not sure why:

@array1 = ("fg", "dg", "tu","ph", "dgs",); @array2 = ("dgs","sfd","dg","ph","rhd"); if (scalar(@array1) >= scalar(@array2)) { @bigger_array = @array1; @smaller_array = @array2; } else { @bigger_array = @array2; @smaller_array = @array1; } $value = 0; foreach $word (@bigger_array) { for (my $i = 0; $i <= scalar(@smaller_array); $i++) { if($word eq $array1[$i]) { splice(@smaller_array,$i, 1); $i--; $value++; } } } print $value;

Does anyone know why? Thanks

Replies are listed 'Best First'.
Re: Comparing arrays and returning number of similar elements
by brian_d_foy (Abbot) on Feb 09, 2006 at 23:25 UTC

    You want the intersection of two arrays. The answer to "How do I compute the intersection of two arrays" in perlfaq4 should help. Good luck :)

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
      Yes, but that assumes that each element in the list is unique.
Re: Comparing arrays and returning number of similar elements
by Mandrake (Chaplain) on Feb 10, 2006 at 04:43 UTC
    Try this.
    my @arr1 =("fg", "dg", "tu","ph", "dgs",,"dg"); my @arr2 = ("dgs","sfd","dg","ph","rhd"); my %hash ; $hash{$_}++ for (@arr1,@arr2) ; print $_ ."\n" for grep {$hash{$_}>1}keys %hash ;
    Thanks..
      Close. You need to count each array separately so that you can distinguish something appearing twice in one array from something that appears once in each array.
      my @arr1 = qw(one one two three four four four); my @arr2 = qw(two four four five five); my %hash ; ++$hash{$_}[0] for @arr1; ++$hash{$_}[1] for @arr2; for (keys %hash) { # Print the smaller count printf "$_ appears %d times in both arrays\n", $hash{$_}[0] < $hash{$_}[1] ? $hash{$_}[0] : $hash{$_}[1] if $hash{$_}[1] and $hash{$_}[0]; }

      Caution: Contents may have been coded under pressure.
Re: Comparing arrays and returning number of similar elements
by planetscape (Chancellor) on Feb 10, 2006 at 07:47 UTC