Purging Logs

Many programs maintain some variety of logs. Often, much of the information in the logs is redundant or just useless. The program shown in Listing 27.7 removes all lines from a file that contain a particular word or phrase, so lines that you know are not important can be purged. For example, you might want to remove all the lines in the Apache error log that originate with your test client machine because you know those error messages were produced during testing.

Listing 27.7. Purging Log Files

#!/usr/bin/perl

# Be careful using this program!

# This will remove all lines that contain a given word

# Usage: remove <word> <file>

[email protected][0]

;

[email protected][1]

;

if ($file) {

# Open file

for reading

open (FILE,

"$file") or die "Could not open file: $!";

@lines=<FILE>;

close FILE;

# Open file

for writing

open (FILE,

">$file") or die "Could not open file for

writing: $!";

for (@lines)

{

print FILE

unless /$word/;

} # End for

close FILE;

} else {

print "Usage

: remove <word> <file>\n";

} # End if...

else

The code uses a few idiomatic Perl expressions to keep it brief. It reads the file into an array using the <file> notation; it then writes the lines back out to the file unless they match the pattern given on the command line.

The die function kills program operation and displays an error message if the open statements fail. $! in the error message, as mentioned in the section on special variables, is the error message returned by the operating system. It will likely be something like 'file not found' or 'permission denied'.

Was this article helpful?

0 0

Post a comment