我有一个名为“boot.log”的文件。我匹配此文件的模式,更改某些关键字,然后将它们写入名为“bootlog.out”的文件。我不确定如何计算所做的更改数量并将其打印到“bootlog.out”。我很确定我需要使用foreeach循环和计数器,但我不知道在哪里。以及如何打印所做的更改。这是我到目前为止所拥有的......
open (BOOTLOG, "boot.log") || die "Can't open file named boot.log: $!";
open (LOGOUT, ">bootlog.txt") || die "Can't create file named bootlog.out: $!\n";
while ($_ = <BOOTLOG>)
{
print $_;
s/weblog/backupweblog/gi;
s/bootlog/backupbootlog/gi;
s/dblog/DBLOG/g;
print LOGOUT $_;
}
close (LOGOUT) || die "Can't close file named bootlog.txt: $!\n";
close (BOOTLOG) || die "Can't close the file named boot.log: $!";
答案 0 :(得分:5)
替换正则表达式返回所做的替换次数。以下是代码的更新副本:
open (my $bootlog, '<', "boot.log") || die "Can't open file named boot.log: $!";
open (my $logout, '>', "bootlog.txt") || die "Can't create file named bootlog.out: $!\n";
my $count = 0;
while (<$bootlog>)
{
print $_;
$count += s/weblog/backupweblog/gi;
$count += s/bootlog/backupbootlog/gi;
$count += s/dblog/DBLOG/g;
print {$logout} $_;
}
close ($logout) || die "Can't close file named bootlog.txt: $!\n";
close ($bootlog) || die "Can't close the file named boot.log: $!";
print "Total items changed: $count\n";