將 ‘a’,’b’,’c’,’c’,’b’,’a’,’a’,’a’,’b’,’b’,’b’ 像 uniq -c 一樣算出同樣字元的各有幾個
use strict; use Data::Dumper; my @arrays = ('a','b','c','c','b','a','a','a','b','b','b'); my %count; map { $count{$_}++ } @arrays; print Dumper \%count;
結果
$VAR1 = { 'c' => 2, 'a' => 4, 'b' => 5 };
或
my @selfs; map { push @selfs ,"${count{$_}} $_"} sort keys(%count); print Dumper \@selfs;
結果
$VAR1 = [ '4 a', '5 b', '2 c' ];
留言
use strict; use Data::Dumper; my @names = qw/joe bob sue bob mike sally mike bob sally dale joe/; # 第一種,較簡化 my %counts; $counts{$_}++ for @names; print Dumper \%counts; # 第二種,較迂迴 my %uniq; foreach (@names) { push @{$uniq{$_}} , 1; } print Dumper \%uniq;