aschwa has asked for the wisdom of the Perl Monks concerning the following question:
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"; } } } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How do I count the number of occurrences of a string in an array?
by pme (Monsignor) on Aug 13, 2015 at 17:09 UTC | |
|
Re: How do I count the number of occurrences of each string in an array?
by karlgoethebier (Abbot) on Aug 13, 2015 at 19:29 UTC | |
|
Re: How do I count the number of occurrences of each string in an array?
by AnomalousMonk (Archbishop) on Aug 13, 2015 at 22:04 UTC | |
|
Re: How do I count the number of occurrences of each string in an array?
by ExReg (Priest) on Aug 13, 2015 at 22:27 UTC | |
|
Re: How do I count the number of occurrences of each string in an array?
by CountZero (Bishop) on Aug 14, 2015 at 06:40 UTC |