use 5.012; use warnings; use Data::Dumper; sub occurrences { my %h; while (my ($i, $k) = each (@_)) { if (! $h {$k}) { $h {$k} = [] } push $h {$k}, $i } return %h } my %h = occurences (2, 1, 3, 4, 3, 4, 4, 5 ); print Dumper (\%h)'