#!/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' };