my %cts; if( $s =~ /^(.*?) (\d+)/ ){ my ($text, $element) = ($1, $2); $cts{$text}++; # OR push @{$cts{$text}}, $element; }