Reputation: 9
I have a file named "boot.log". I'm pattern matching this file, making changes to certain keywords, and then writing them to a file named "bootlog.out". I'm not sure how I can count the number of changes made and print them to "bootlog.out". I'm pretty sure I need to use a foreeach loop and a counter, but I'm not sure where. And how to print those changes made. Here's what I have so far...
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: $!";
Upvotes: 0
Views: 96
Reputation: 34954
The substitution regex returns the number of substitutions made. Here is an updated copy of your code as an example:
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";
Upvotes: 5