#!/usr/local/bin/perl -w use strict; $|++; # array of non-unique words my @non_unique = ('bob and sue', 'bobcat', 'carpet', 'bob', 'car', 'carpet'); # create empty pseudo-hash # hash key is unique word, hash value is array index, array value is count my $ph = [{},]; for(@non_unique) { if(exists $ph->{$_}) # if word already in hash, { $ph->{$_}++; # increment word count } else # else { $ph->[0]{$_} = @$ph; # set hash key to last array index (end of array) $ph->{$_}++; # increment word count to 1 # or in one line... (a little obfuscated) # $ph->[$ph->[0]{$_} = @$ph]++; } # or on one line... (a little more obfuscated - not recommended) # exists $ph->{$_} ? $ph->{$_}++ : $ph->[$ph->[0]{$_} = @$ph]++; } # or on one line... (even more obfuscated - really not recommended) # map{exists$ph->{$_}?$ph->{$_}++:$ph->[$ph->[0]{$_}=@$ph]++}@non_unique; # array of unique words, same order as non-unique words # (the extraction procedure looks a little messy) # it says, for the keys of the hash section of the pseudo-hash, # sort by the value, ascending my @unique = sort { $ph->[0]{$a} <=> $ph->[0]{$b} } keys %{$ph->[0]}; # pretty formatted output of unique array and word count format SortedWordsAndCountHeader = Words Count . format SortedWordsAndCount = @<<<<<<<<<<<<<<<<<< @>>>> $_, $ph->{$_} . $^ = "SortedWordsAndCountHeader"; $~ = "SortedWordsAndCount"; write for @unique;