SaltedPork
SaltedPork

Reputation: 377

How do i count the number of specific letters in an array, Perl?

I have an array which only has letters in it, no digits. I want to count the number of times a specific letter shows. I don't want to use a hash, i need to preserve the order of the list.

use strict;
use warnings;

my %counts;
$counts{$_}++ for @array;
print "$counts\n";

Upvotes: 0

Views: 584

Answers (3)

Dave Cross
Dave Cross

Reputation: 69244

The code that you have seems to work find for counting the occurrences. The only problem you have is in displaying the counts. You're using a new scalar variable called $counts which is undeclared and empty.

What you want is this:

use strict;
use warnings;

my %counts;
$counts{$_}++ for @array;
print "$_: $counts{$_}\n" for keys %counts;

Upvotes: 2

jira
jira

Reputation: 3944

You might consider Text::CountString module on CPAN.

Upvotes: 1

mkHun
mkHun

Reputation: 5927

Use grep for to do it

my @ar = qw(abc cde fgh 123 abc);
my $count = grep{ /ab/} @ar;
print $count;

Or else use foreach

my @ar = qw(abc cde fgh 123 abc);
my $m;
$m+= /ab/,foreach (@ar);
print $m;

While the match was encountered $m will increment.

Upvotes: 1

Related Questions