Jenda Krynicky wrote:
>
> From: "John W. Krahn" <[EMAIL PROTECTED]>
> >
> > perl
> > -lane'eof||m!^\d{4}/\d\d/\d\d\s+\d\d:\d\d:\d\d\s!?((@X&&print"@X"),@X=
> > @F):push@X,@F' logfiles*
>
> Wow :-)
>
> It's very short and all, but ... not very readable :-)
>
> Let's write it as an ordinary program:
>
> #!perl -w
> use strict;
>
> sub CleanupLog {
> my ($from_file, $to_file) = @_;
> open my $IN, '< ' . $from_file
Since you are using lexically scoped file handles we can also use the
three argument form of open.
open my $IN, '<', $from_file
> or die "Can't open file $from_file : $!\n";
> open my $OUT, '> ' . $to_file
> or die "Can't create file $to_file : $!\n";
> my $line = '';
> while (<$IN>) {
> chomp; # get rid of the newline
> next if $_ eq ''; # skip empty lines
What happens if $_ eq ' '?
> s/\s{2,}/ /g; # replace 2 or more whitespace chars
> # with a single space
Or simply:
s/\s+/ /g;
Or for speed:
tr/ \t\r\n\f/ /s;
> if ( m{^\d{4}/\d{2}/\d{2} \d\d:\d\d:\d\d} ) {
> # if the current line starts with a timestamp ...
> # I assume the YYYY/MM/DD HH:MI:SS format
> print OUT $line, "\n" if $line;
^^^
Unknown file handle?
> # print the buffer
> $line = $_;
> # remember the current line
> } else {
> $line .= ' ' . $_;
> # add the current line to the buffer
> }
> }
> print $OUT $line, "\n" if $line;
> # print the last buffer
> close $IN;
> close $OUT;
> }
A more exact translation would be:
sub CleanupLog {
my ( $from_file, $to_file ) = @_;
open my $IN, '<', $from_file or die "Cannot open file $from_file:
$!";
open my $OUT, '>', $to_file or die "Cannot create file $to_file:
$!";
my @output;
while ( <$IN> ) {
my @line = split; # removes ALL whitespace
if ( m!^\d{4}/\d\d/\d\d\s+\d\d:\d\d:\d\d\s! ) {
print $OUT "@output\n" if @output;
@output = @line;
}
else {
push @output, @line;
}
}
print $OUT "@output\n" if @output;
close $IN;
close $OUT;
}
> # now let's process all .log files in the current directory and
> # write the results to 'Cleaned' subdirectory
> mkdir 'Cleaned', 0777 unless -d 'Cleaned';
> opendir my $DIR, '.';
You should _always_ verify that the directory was opened.
opendir my $DIR, '.' or die "Cannot opendir '.': $!";
> while (defined(my $file = readdir $DIR)) {
> next unless $file =~ /\.log$/i;
> # skipp all files that do not end with '.log'
> next if -d $file; # skip directories
> print "$file\n";
> CleanupLog $file, 'Cleaned/'.$file;
> }
> closedir $DIR;
> __END__
>
> Of course you'll have to read some introductory docs to be able to
> modify this to fit better to your needs, but this should give you a
> start.
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]