use strict;
my %hash=();
print "Enter words one by line, terminate by ^Z or ^D\n";
my $l;
while ($l=<STDIN>)
{
chomp($l);
if (defined $hash{$l})
{ $hash{$l}=1+$hash{$l};
}
else
{ $hash{$l}=1;
}
}
my $index;
my @hash_indexes = keys(%hash);
print "\n\nHASH CONTENTS UNSORTED:\n";
foreach $index (@hash_indexes)
{
print $index."\t => ".$hash{$index}."\n";
}
print "\n\nHASH CONTENTS SORTED BY INDEX, ASCENDING:\n";
my @s1 = sort @hash_indexes;
foreach $index (@s1)
{
print $index."\t => ".$hash{$index}."\n";
}
print "\n\nHASH CONTENTS SORTED BY CONTENTS, DESCENDING:\n";
my @s2 = sort { $hash{$b} <=> $hash{$a} } @hash_indexes;
foreach $index (@s2)
{
print $index."\t => ".$hash{$index}."\n";
}
'
C:\TEMP>perl -w t.pl
Enter words one by line, terminate by ^Z or ^D
hello
hello
once
again
I
like
this
program
very
very
much
and
hello
one
again
and
again
and
over
and
over
again
and
bye
now
^Z
HASH CONTENTS UNSORTED:
very => 2
like => 1
again => 4
bye => 1
over => 2
hello => 3
one => 1
now => 1
this => 1
I => 1
and => 5
once => 1
much => 1
program => 1
HASH CONTENTS SORTED BY INDEX, ASCENDING:
I => 1
again => 4
and => 5
bye => 1
hello => 3
like => 1
much => 1
now => 1
once => 1
one => 1
over => 2
program => 1
this => 1
very => 2
HASH CONTENTS SORTED BY CONTENTS, DESCENDING:
and => 5
again => 4
hello => 3
very => 2
over => 2
bye => 1
one => 1
now => 1
this => 1
I => 1
like => 1
once => 1
much => 1
program => 1
C:\TEMP>
';