I’m trying to assemble a script that will first identify the newest log file created under a folder, then open it and look for specific data. Basically, I will be looking in this log file for a specific error and print the errors into the new log file.
I understand how to perform sort in order to have the most recent file, but having trouble in reading the latest file and copying it to the new log file
use File::stat;
$dirname = 'C:/Luntbuild_Logs';
$timediff = 0;
opendir DIR, "$dirname";
while ( defined( $file = readdir(DIR) ) ) {
if ( $file ne "." && $file ne ".." ) {
$diff = time() - stat("$dirname/$file")->mtime;
if ( $timediff == 0 ) {
$timediff = $diff;
$newest = $file;
}
if ( $diff < $timediff ) {
$timediff = $diff;
$newest = $file;
}
}
}
print $newest;
$file1 = "$dirname/$file";
open( FILE1, "<$newest" );
my (@fprint) = <FILE1>;
close FILE1;
open( FOUT, ">list1.txt" ) || die("Cannot Open File");
foreach $line (@fprint) {
print "$line" if $line =~ /> @/;
print "$line" if $line =~ /ORA-/;
print FOUT $line;
}
close FOUT;
The primary problem is that you build the full file path in
$file1but then open$newestwhich contains only the file name.You really should improve your code by
Always using
use strictanduse warningsat the start of your program, and declaring all variables withmyat their point of definitionUse lexical file and directory handles and the three-parameter form of open. Always test the status of an open and put
$!in thediestring so that you know why it failedNever put double-quotes around a variable unless you know what it does and that is what you want
Here is a refactoring of your code which follows these guidelines and also uses the built-in
-Moperator that returns the age of a file in days