I'm new to coding and perl and am stuck with a problem. I've looked in other threads and googled the problem but I haven't found a solution yet. Part of my concern is that I'd like to understand why it's not working rather than just getting a quick fix to the problem. I want this code to count the number of times that each string in an array appears in that array. So, as an example, if-

@array = qw('dog', 'cat', 'sheep', 'dog', 'dog', 'cat');

It would return

>dog, 3 >cat, 2 >sheep, 1

The code that I'm using is below. Currently, for any input, it only gives a count of "1" as the number of occurrences in the array. I know this to be false as I've created test arrays with multiple identical values. What am I doing wrong, Monks?

use strict; use warnings; my $i; my $j; my @data; for my $file (@ARGV) { open (RAW, "./$file") || die "Cannot open specified file to be process +ed\n"; while(<RAW>) { @data = join('', $_ =~ /^(\d\d\d\d)-(\d\d)-(\d\d) (\d+):(\d+): +(\d+)/); for $i (@data) { my $cnt = 0; for $j (@data){ if ($i eq $j) { $cnt = $cnt + 1; print "$i, $j, $cnt\n"; } } } } }

In reply to How do I count the number of occurrences of each string in an array? by aschwa

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.