I have written a Perl program which will match certain words in a log file and store the results in a database. The problem is this program works fine with a small file but doesn’t work with file size ~2GB. Is it size or program need to be changed?
use POSIX qw(strftime);
# load module
use DBI;
open( FILE, "/root/temp.log" ) or die "Unable to open logfile:$!\n";
$count_start = 0;
$count_interim = 0;
$count_stop = 0;
while (<FILE>) {
@test = <FILE>;
foreach $line (@test) {
if ( $line =~ m/server start/ ) {
#print "yes\n";
$count_start++;
}
elsif ( $line =~ m/server interim-update/ ) {
$count_stop++;
}
elsif ( $line =~ m/server stop/ ) {
$count_interim++;
}
}
print "$count_start\n";
print "$count_stop\n";
print "$count_interim\n";
$now_string = strftime "%b %e %H:%M:%S", localtime;
print $now_string;
# connect
my $dbh = DBI->connect( "DBI:Pg:dbname=postgres;host=localhost",
"postgres", "postgres", { 'RaiseError' => 1 } );
# execute INSERT query
my $rows = $dbh->do(
"insert into radcount (acc,bcc,dcc) Values ('$count_start','$count_stop','$count_interim')"
);
print "$rows row(s) affected\n";
# clean up
$dbh->disconnect();
}
close(LOG);
I have a few comments about your program.
Always
use strictanduse warningsat the start of your program, and declare variables usingmyat their point of first useAlways use lexical filehandles and the three-parameter form of
open, and always check the status of an open callYou are opening the file using filehandle
FILE, but closingLOGYour
whilestatement reads the first line of the file and throws it away@test = <FILE>attempts to read all of the rest of the file into the array. This is what is causing your problemYou should connect to the database once and use the same database handle for the rest of the code
You should use
prepareyour statement with placeholders and pass the actual values withexecuteYou are incrementing
$count_stopfor aninterim-updaterecord and$count_interimfor astoprecordThe core module
Time::Pieceprovides astrftimemethod without the bloat ofPOSIXHere is a modification of your program to show these ideas. I have not set up a log file and database to test it but it looks fine to me and does compile.