Mar 23, 2013

Create Log File in Perl


Today we discuss about how to create a log file in Perl, Logging is always part and parcel in developing code.

Here in the below mentioned example : 
1) We are trying to read the lines from the file in the path 'C:\Perl\data.txt'
2) While reading the lines, in case of any errors, we are capturing (means we are writing to log file) to log file 'C:\Perl\log.txt'
3) You can either use write/append mode to log file based on your requirement.
4) Write (">") mode : You write the content to a new log file
5) Append (">>") mode : if Log File already exists, you append the content to the existing file

log_test.pl

#!/usr/bin/perl

use strict;
use warnings;

my $log_file_path = 'C:\Perl\log.txt';
my $read_file_path = 'C:\Perl\data.txt';

#use the ">"  symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
open (LOG_FILE, ">$log_file_path"); 

open (READ_FILE, "$read_file_path"); 
#"READ_FILE" is File Handle

unless (-e $read_file_path) {
    print LOG_FILE "\n Read File Doesn't Exist!!! : "  . $read_file_path;
    exit;


#use the ">"  symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
while my $each_line (<READ_FILE>) {
     print "\n Each Line: :" . $each_line;
}

print LOG_FILE "\nTesting Writing into Perl file";
print LOG_FILE "\nWriting more content 111";
print LOG_FILE "\nWriting more content 222";

close (READ_FILE); 
close (LOG_FILE);

O/P:
log.txt (In case file data.txt is present in the path)
Testing Writing into Perl file
Writing more content 111
Writing more content 222

log.txt (In case file data.txt is not present in the path)
Read File Doesn't Exist!!! : log.txt


No comments:

Post a Comment