c:\@Work\Perl\monks>perl use strict; use warnings; use Data::Dump qw(dd); # for debug my $text = <<'EOT'; Now is the time, now is the hour. The rain in Spain falls mainly in Spain. The rain in Spain falls mainly in Spain. Foo foo foo Bar bar bar FOO BAR FOO BAR EOT print "[[$text]] \n"; # for debug my $rx_word = qr{ \S+ }xms; my @words = $text =~ m{ $rx_word }xmsg; # dd \@words; # for debug my %word_count; ++$word_count{$_} for @words; # dd \%word_count; # for debug my @sorted = sort { $a->[0] cmp $b->[0] # sort first by alpha ascending or $a->[1] <=> $b->[1] # then by frequency ascending } map [ $_, $word_count{$_} ], keys %word_count ; dd \@sorted; # for debug print "'$_->[0]' ($_->[1]) \n" for @sorted; __END__ [[Now is the time, now is the hour. The rain in Spain falls mainly in Spain. The rain in Spain falls mainly in Spain. Foo foo foo Bar bar bar FOO BAR FOO BAR ]] [ ["BAR", 2], ["Bar", 1], ["FOO", 2], ["Foo", 1], ["Now", 1], ["Spain", 2], ["Spain.", 2], ["The", 2], ["bar", 2], ["falls", 2], ["foo", 2], ["hour.", 1], ["in", 4], ["is", 2], ["mainly", 2], ["now", 1], ["rain", 2], ["the", 2], ["time,", 1], ] 'BAR' (2) 'Bar' (1) 'FOO' (2) 'Foo' (1) 'Now' (1) 'Spain' (2) 'Spain.' (2) 'The' (2) 'bar' (2) 'falls' (2) 'foo' (2) 'hour.' (1) 'in' (4) 'is' (2) 'mainly' (2) 'now' (1) 'rain' (2) 'the' (2) 'time,' (1)