#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use List::MoreUtils qw(uniq); my $re = "iowq john stepy andy anne alic bert stepy anne bert andy step alic andy"; my $i = 0; my %hash = map { ++$i => $_ } uniq split(/\s+/, $re); print Dumper \%hash; __END__ perl test.pl $VAR1 = { '6' => 'alic', '8' => 'step', '1' => 'iowq', '4' => 'andy', '2' => 'john', '7' => 'bert', '5' => 'anne', '3' => 'stepy' }; #### #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; my $re = "iowq john stepy andy anne alic bert stepy anne bert andy step alic andy"; my @names = split(/\s+/, $re); map($hash{$_}++, @names); # $hash{$_}++ foreach @names; # alternative instead of map print Dumper \%hash; __END__ $ perl test.pl $VAR1 = { 'bert' => 2, 'anne' => 2, 'alic' => 2, 'john' => 1, 'andy' => 3, 'step' => 1, 'iowq' => 1, 'stepy' => 2 };