Jump to content

Perl Programming/Exercise 3 Answers

From Wikibooks, open books for an open world

Reading and writing files

[edit | edit source]
open FDESC1, "<", "./first_file.log" or die $!;
open FDESC2, ">", "./second_file.log" or die $!;
while (<FDESC1>) {
        print FDESC2 $_;
}
close FDESC2;
close FDESC1;

Using regular expressions to search text

[edit | edit source]
open FH, "<", "book.txt" or die $!;

my $chapter_count = 0;
my %chapter_lines; 
my $in_chapter = 0; #to skip the prologue etc.
my $line_count = 0; #of each chapter
my $chapter; #name

my @repetitions; #word repetitions
my @special; #words starting with de, ending with vowels
my @numbers; #integers and floats that appear in text

while (<FH>) {
	
	if ($_ =~ m/\b(\w+)\s\1\b/i) {
		push(@repetitions, $1);
	}
	
	if ($_ =~ m/((-)?\d+(\.\d+)?)/) {
		push(@numbers, $1);
	}
	
	if ($_ =~ m/\s((de)\S*(a|e|i|o|u))\s/) {
		push(@special, $1);
	}
	
	if ($_ =~ /^CHAPTER/i) {
		$chapter_count++;
		$in_chapter = 1;
		
		if ($chapter_count == 1) {
			chomp($_);
		 	$chapter = $_;
			$chapter_lines{$chapter} = 0;
		}
		if ($chapter_count > 1) {
			$chapter_lines{$chapter} = $line_count;
			chomp($_);
		 	$chapter = $_;
			$line_count = 0;
		}
		
	}
	
	if ($_ !~ /^CHAPTER/i) {
		if ($in_chapter == 1) {
			$line_count++;
		}
		
	}
	
}

print "This book contains ".$chapter_count." chapters.\n\n";

foreach (sort keys(%chapter_lines)) {
	print $_." contains ".$chapter_lines{$_}." lines.\n";
}

$" = "\n";
print "\nRepetitions:\n@repetitions\n\n";

my %hash   = map { $_, 1 } @numbers;
@numbers = sort keys %hash;
print "Numbers:\n@numbers\n\n";

print "\nSpecial matches:\n@special\n\n";

close FH;