Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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 (waldo@cyberspace.org)
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 (waldo@cyberspace.org)
# Big Willy on perlmonks.org
# 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";
}
 

Comment on Frequency Analyzer
Download Code
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?
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 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

Back to Code Catacombs

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2014-08-31 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls