Category: Cryptography and Text Processing
Author/Contact Info Will Stockwell (
Description: Updated as of March 16, 2001 at 0120 UTC Does frequency analysis of a monoalphabetic enciphered message via STDIN. (Thanks to Adam for the $i catch).
#!/usr/bin/perl -w
# Frequency Analyzer by Will Stockwell (
# Big Willy on
# Thanks to japhy for the split //, lc business
# Thanks to Adam for the $i catch

my %letters;

while (<STDIN>) {
        $letters{$_}++ for split //, lc;

foreach (sort keys %letters) {
        if($_ eq "\n") { 
                print "\\n";
        } elsif($_ eq ' ') {
                print "<space>";
        } elsif($_ eq "\t") {
                print "\\t";
        } else {
                print "$_";
        print " = $letters{$_}\n";
Replies are listed 'Best First'.
Re: Frequency Analyzer
by japhy (Canon) on Mar 16, 2001 at 15:38 UTC
    Your s/// for converting characters to lowercase is far too much work, and the use of $& is poisonous. I'd use the lc() function.

    And you're using substr() where chop() would do, and probably where you could just use split().

    while (<STDIN>) { $count{$_}++ for split //, lc; }
    Is how I would optimize your input loop.

    japhy -- Perl and Regex Hacker
Re: Frequency Analyzer
by Chmrr (Vicar) on Mar 16, 2001 at 01:27 UTC

    Interesting that you should bring this up. In my "AP Computer Science" class (unfortunatly taught in C), the teacher promised that one of the harder projects later in the year would be to do this exact problem. Within 2 minutes I turned in the following code:

    perl -ne 'chomp;$c{$_}++ for split//;}print map {"$_:$c{$_}\n"} sort keys %c;{'

    ..which is a cruder version of what you have above. Whenever I can, I enjoy putting pained looks on the other student's faces as I hand-write in pencil my code, whilst they print out reams of paper.. :)

    perl -e 'print "I love $^X$\"$]!$/"#$&V"+@( NO CARRIER'

Re: Frequency Analyzer
by merlyn (Sage) on Mar 15, 2001 at 23:38 UTC
Re: Frequency Analyzer
by Adam (Vicar) on Mar 16, 2001 at 01:08 UTC
    What purpose does $i serve in your code?