Perl Programming/Simple examples 1

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: Humour Index Next: Simple examples 2

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.

I have added a bit to this code to enable the user to create a report of the data if they wish:

print "Here are your results:\n";

foreach my $key (sort keys %chars) {
	print "$key appeared ", ($chars{$key} == 1 ? "once\n" : "$chars{$key} times\n");
};

print("Would you like to print a report of this? \n");
chomp(my $answer = <STDIN>);
print("And would you like me to highlight any specific letter?\n");
chomp(my $letterPattern = <STDIN>);

unless ($answer eq "no" or $answer eq "nope") { #opens and writes to a file, if the file doesn't exist the program will automatically create one
	open(my $fh, '>', 'report.txt') or die "something went wrong.";	# Once the file is open, we can then print/write to it by simply typing print (duhh..) followed by the scalar name
	print $fh "Here is the report:\n";

	if (scalar(@arrayForReport) == 0) {
		print $fh "FAILED DUE TO BAD DATA INPUT";	# If there is no data in the input file, rather than printing a blank report, the program will print a failure message
	} else {
		foreach my $key (sort keys %chars) {
			print $fh "$key appeared ", ($chars{$key} == 1 ? "once\n" : "$chars{$key} times\n");	# the same as what we saw above for printing results
		};# obviously I could have just made this into a subroutine, but I am lazy ;P
		
		print $fh "\n";
		
		#This could be better, but if the user types more than one letter for a search it will not work anyway, so it isn't really wrong or a problem.
		if ($letterPattern eq "no" or $letterPattern eq "No") {
			print $fh "original text = @arrayForReport\n";
		} else {
			print $fh "Original text: ";
			
			foreach (@arrayForReport) {
				if ($_ eq $letterPattern) { #If the letter in the array is the same as the one the user is looking for:
					print $fh "(", uc $_, ")";	# still print it but put brackets around it and uc (uppercase) it
				} else {
					print $fh $_;	# if it isn't the letter the user is looking for, just print it normally
				}
			};
		}
		print $fh "When asked if you wanted a report, you said: $answer";
		print "Report successfully created.\n";	# This just lets us know that the process went well and everything that was expected to happen, happened.
	};
};


Previous: Humour Index Next: Simple examples 2