10.10. Count words

  • %hash, $hash{element}

  • keys

Example 10-2. examples/hashes/count_words_hash.pl

#!/usr/bin/perl
use strict;
use warnings;

my $filename = shift or die "Usage: $0 filename\n";

my %count;

open(my $fh, "<", $filename)
    or die "Could not open '$filename': $!"; 
while (my $line = <$fh>) {
    chomp $line;
    my @words = split " ", $line;
    foreach my $word (@words) {
        $count{$word}++;
    }
}



foreach my $word (keys %count) {
    print "$word : $count{$word}\n";
}

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed