Perl Programming/Simple Examples 1

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

This script counts the number of occurences of each letter in a file:

#!/usr/bin/perl
# always enable compiler warnings, as they may highlight potential trouble
use warnings;
# let's ask the compiler to be more strict, make sure we declare our variables etc.
use strict;
 
# This statement prompts the user for a filename to read from.
print "What file would you like to read from?\n";
 
# This statement assigns whatever is given on the standard input(usually your keyboard) to a scalar
# variable named $filename and removes the newline character that is included by default.
chomp (my $filename = <STDIN>);
 
# This line opens the file referred to in $filename for input via a lexical filehandle
# stored in a scalar variable named "$file".
open my $file, "<", $filename or die "Can't open '$filename' for reading: $^E\n";
 
# This loop goes through each line of the file, splits the line into separate characters and
# increments the number of occurrences of each letter using a hash called "%chars".
 
my %chars;
while(<$file>) {
    $_ = lc($_); # convert everything to lowercase
    my @characters = split (//, $_);  # Store list of characters in an array
    foreach (@characters) {
        if(/\w/) {                    # Ignore all characters except letters and numbers
            $chars{$_}++;
        }
    }
}
close $file;
 
# This loop goes through each letter in the %chars hash and prints a report informing the user of
# how many times each letter occurred.
 
foreach my $key (sort keys %chars) {
    if($chars{$key} == 1) {
        print "$key appeared once.\n";
    } else {
        print "$key appeared $chars{$key} times.\n";
    }
}

If you executed this program on a file containing the sentence "The quick, brown fox jumps over the lazy dog.", you would see this as output:

a appeared once.
b appeared once.
c appeared once.
d appeared once.
e appeared 3 times.
f appeared once.
g appeared once.
h appeared 2 times.
i appeared once.
j appeared once.
k appeared once.
l appeared once.
m appeared once.
n appeared once.
o appeared 4 times.
p appeared once.
q appeared once.
r appeared 2 times.
s appeared once.
t appeared 2 times.
u appeared 2 times.
v appeared once.
w appeared once.
x appeared once.
y appeared once.
z appeared once.