跳转到内容

Perl 编程/练习 3 答案

来自维基教科书,自由的教科书

读取和写入文件

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

使用正则表达式搜索文本

[编辑 | 编辑源代码]
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;
华夏公益教科书