1

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.

4

4 回答 4

7

我认为我们可以使用

map {$count{$_}++;} @array;

代替

foreach(@array)
{
    unless(defined($count{$_}))
    {
        $count{$_} = 1;
    }
    else {
        $count{$_}++;
    }
}

来简化代码。

于 2013-07-26T07:38:20.977 回答
5

“如何输出数组中每个重复字符串的计数?”

#!/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

请注意,那个“孤儿”没有被输出。

于 2013-07-26T07:24:21.317 回答
4

使用 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;
于 2013-07-26T09:28:43.507 回答
1

试试这个更短的代码你不会得到任何比这更短的东西

my @array = ('cookies','balls','cookies','balls','balls');
my $hashh = {};
foreach (@array){
       if(exists $hashh->{$_}){
               $hashh->{$_}++;
       } else{
               $hashh->{$_} = 1;
       }
}
print Dumper($hashh);
于 2013-07-26T07:56:30.720 回答