I have an array that is like
my @array = ('cookies','balls','cookies','balls','balls');
but the real one is much bigger/longer.
How do I output the count of each repeated string in the array?
like in the example, cookies is 2 and balls is 3.
我认为我们可以使用
map {$count{$_}++;} @array;
代替
foreach(@array)
{
unless(defined($count{$_}))
{
$count{$_} = 1;
}
else {
$count{$_}++;
}
}
来简化代码。
“如何输出数组中每个重复字符串的计数?”
#!/usr/bin/perl
use strict;
use warnings;
my @array = ('cookies','balls','cookies','balls','balls', 'orphan');
my %count;
$count{$_}++ foreach @array;
#removing the lonely strings
while (my ($key, $value) = each(%count)) {
if ($value == 1) {
delete($count{$key});
}
}
#output the counts
while (my ($key, $value) = each(%count)) {
print "$key:$value\n";
}
印刷:
cookies:2
balls:3
请注意,那个“孤儿”没有被输出。
使用 Perl 比其他一些答案更惯用...
use strict;
use warnings;
use 5.010;
my @array = ('cookies','balls','cookies','balls','balls');
my %count;
$count{$_}++ foreach @array;
say "$_: $count{$_}" foreach grep { $count{$_} != 1 } keys %count;
试试这个更短的代码你不会得到任何比这更短的东西
my @array = ('cookies','balls','cookies','balls','balls');
my $hashh = {};
foreach (@array){
if(exists $hashh->{$_}){
$hashh->{$_}++;
} else{
$hashh->{$_} = 1;
}
}
print Dumper($hashh);