Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Frequency Analyzer

by Big Willy (Scribe)
on Mar 16, 2001 at 04:00 UTC ( #64842=sourcecode: print w/replies, xml ) Need Help??
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 20: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 06: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 16, 2001 at 04:38 UTC
Re: Frequency Analyzer
by Adam (Vicar) on Mar 16, 2001 at 06:08 UTC
    What purpose does $i serve in your code?

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://64842]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2021-10-23 05:56 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (87 votes). Check out past polls.