$ perl -Mstrict -Mwarnings -e ' use Data::Dumper; sub occurences { my ($i, %h) = 0; push @{$h{$_}}, $i++ for @_; \%h } my $h = occurences(2, 1, 3, 4, 3, 4, 4, 5); print Dumper $h; ' $VAR1 = { '4' => [ 3, 5, 6 ], '1' => [ 1 ], '5' => [ 7 ], '2' => [ 0 ], '3' => [ 2, 4 ] };