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

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.