sub toBagOfWords { my %bag; $bag{$_}++ for split /\s+/, shift; %bag; } my %hash = toBagOfWords "I see their knavery this is to make an ass of me"; my @words = keys %hash; # if you still need the list of word, in a "random" order