简体   繁体   English

如何计算Perl数组中特定字母的数量?

[英]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";

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. 您正在使用一个名为$counts的新标量变量,该变量未声明且为空。

What you want is this: 您想要的是:

use strict;
use warnings;

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

Use grep for to do it 使用grep做到这一点

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

Or else use foreach 否则使用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. 在遇到匹配项时, $m将递增。

您可以考虑在CPAN上使用Text :: CountString模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM