in reply to Hash to count characters

amittleider:

Just for grins, here's another way to do it:

#!/usr/bin/perl use strict; use warnings; my %charCount; my $corpus = join('', <DATA>); $corpus =~ tr/A-Z/a-z/d; # Map uppercase to lowercase $corpus =~ tr/a-z//cd; # Delete all but lowercase $charCount{$_}++ for split //, $corpus; for (sort keys %charCount) { print "$_ : $charCount{$_}\n"; } __DATA__ Now is the time for all good men to come to the aid of their party. The quick red fox jumped over the lazy brown dog. The warrior swings the +6 axe at the orcs standing in front of him.

...roboticus

Replies are listed 'Best First'.
Re^2: Hash to count characters
by Anonymous Monk on Aug 12, 2010 at 20:11 UTC
    Whoa! So many great ideas so fast. You monks really are lifesavers! Here's the final working code! (I'll be sure to use strict and warnings in the future!)
    print "Counting from @ARGV \n"; &countWords(); &countChar(); sub countWords() { open DAT, "< @ARGV[0]" or die "Can't open @ARGV : $!"; print "Word Count\n"; while($line = <DAT>){ my @line_words = split(/\W/, $line); foreach my $word (@line_words){ if ($wordCount{$word}){ $wordCount{$word}++; }else { $wordCount{$word}=1; } } } close(DAT); for $word (sort keys %wordCount) { print "$word => $wordCount{$word}\n"; } } sub countChar() { open DAT, "< @ARGV[0]" or die "Can't open @ARGV : $!"; print "Character count\n"; while ($line = <DAT>){ my @line_words = split (//, $line); foreach my $char (@line_words){ if ($charCount{$char}){ $charCount{$char}++; }else { $charCount{$char}=1; } } } for $char (sort keys %charCount) { next unless $char =~ /[a-zA-Z]/; print "$char => $charCount{$char}\n"; } close(DAT); }
    <3<3 AJ