#!/usr/local/bin/perl use strict; use warnings; our %word_hash; # used to determine which word should be listed first. sub word_hash_compare { #print "$a --- $b\n"; # If words $a and $b have the same frequency, then the # work that comes first in the alphabet is "smaller". if ($word_hash{$a} == $word_hash{$b}) { # $a cmp $b returns -1 if $a < $b, 1 if $b > $a, and 0 if they are equal.. return $a cmp $b; } # if words $a and $b have different frequencies, then the # larger frequency should come first. # the perl operator $x <=> $y returns -1 if $x < y, 1 if $y < $x, and 0 if they are equal return $word_hash{$b} <=> $word_hash{$a}; } # # main # # process each line on the standard input. while(my $line = <>) { # for each word in the line. foreach my $word (split(/\s+/, $line)) { # conver to all lower-case my $lc_word = lc($word); $word_hash{$lc_word}++; } # end for } # end while foreach (sort word_hash_compare keys %word_hash) { print "$word_hash{$_}\t$_\n"; }