1. 下面一段代码,实现功能为:读入一个或多个文件,列出每个文件中的所有单词,并给出每个单词出现的次数。命令格式: perl words_count [file1] [file2] ... [filen]
#! /usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
#print "please enter a file name: \n";
#chomp (my $file = <>);
while (@ARGV) {
my $file = shift;
open (RFILE, $file) || die "can't open $file: $!";
my @data = <RFILE>;
close (RFILE);
my %words_list = ();
foreach my $line (@data) {
while ($line =~ s/\b(\w+)\b//) {
if (exists $words_list{$1}) {
$words_list{$1}++;
}
else {
$words_list{$1} = 1;
}
}
}
print Dumper(\%words_list);
}
2. 修改一个文件,并自动生成后缀名为.bak原文件的备份文件
#! /usr/bin/perl
use warnings;
use strict;
$^I = ".bak";
while (<>) {
s/^professor/student/;
print;
}