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.
I think we can use
map {$count{$_}++;} @array;
instead of
foreach(@array)
{
unless(defined($count{$_}))
{
$count{$_} = 1;
}
else {
$count{$_}++;
}
}
to simplify the code.
map in a void context is a bad idea. I'd write that as $count{$_}++ foreach @array.$count{$_}++ for @array."How do I output the count of each repeated string in the array?"
#!/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";
}
Prints:
cookies:2
balls:3
Mind, that 'orphan' wasn't output.
cookies:2 /n balls:3?Try this more shorter code u will not get any thing shorter than this
my @array = ('cookies','balls','cookies','balls','balls');
my $hashh = {};
foreach (@array){
if(exists $hashh->{$_}){
$hashh->{$_}++;
} else{
$hashh->{$_} = 1;
}
}
print Dumper($hashh);
if ... else would be shorter. If $hashh->{$_} doesn't exist, it'll automatically be created when you increment it. $hashh->{$_}++ for @array;$hashh->{$_}++ for @array is quite a lot shorter than your foreach loop :-)