my @str= qw(ssg.nal ssg_00.nsr ssg_00.nsn ssg_00.nss xxx_01.txt xxx_03.dat); my %starts; foreach (@str) { #increment the value for the hash element that has the #prefix as a key. $starts{$1}++ if /^([a-zA-Z0-9]+)/; } # print all the prefixes and number of files associated foreach (keys %starts) { print "$_ = $starts{$_}\n"; }