I would probably do it like this:
use strict; use warnings; my @array1 = qw/ jed jethro zed zug /; my @array2 = qw/ jed jed jed zack zed zug zug /; print join(':', @$_), "\n" for count_occurrences( \@array1, \@array2 ) +; sub count_occurrences { my( $wanted, $have ) = @_; my %counter; @counter{@$wanted} = (0)x@$wanted; $counter{$_}++ for @$have; return map { [ $_ => $counter{$_} ] } @$wanted; }
The output is:
jed:3 jethro:0 zed:1 zug:2
Notice how this method first sets counters to zero for all elements in @array1. Then it adds a count of those names in @array2 that appeared in @array1. Then a data structure is returned, and we print it.
The nuance here is that if a name appears in @array2 but not in @array1, it won't show up in the final count. After reading your question a couple of times, I got the impression that this behavior would be desirable. Another nuance is that the output will appear in the original order of names from @array1.
Dave
In reply to Re: Compare elements from two arrays and count
by davido
in thread Compare elements from two arrays and count
by skalman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |