Hey all! New to PerlMonks and Perl in general. I have been trying to create a script as a side project (personal knowledge, no monetary gain) that goes through about 30 files and pulls out lines that match a specific set of search criteria.
My code works, but I wanted to ask if there is a more "clean" way to do it.
1) I set some variables for the HTML report and the log file. Currently I don't have any HTML syntax being written, that will come later once I get everything nailed down.
2) I create the two files that I am going to be writing to.
3) I check to see if the file exists. If it does, I open the HTML file and the log file for appending. If it doesn't, I write to the log file
4) I pull out only the lines I want, and then write them to the HTML file.
5) I close the HTML file and the log file.
#!/usr/bin/perl use warnings; use strict; use 5.010; use Time::Local; my $file_01_txt = "file_01.txt"; ($sec, $min, $hour, $mday, $mon, $year, $j1,$j2, $j3) =localtime(time) +; $year = $year+1900; $mon = $mon+1; $outfolder = "REPORT_output\_$year\_$mon\_$mday\_\_$hour\_$min\_$sec"; mkdir $outfolder; mkdir "$outfolder/log"; $html_file = <$outfolder/REPORT.html>; $log_file = <$outfolder/log/log.txt>; open($html_report, '>', $html_file) or die "Cannot open file $html_fil +e"; open($log_report, '>', $log_file) or die "Cannot open file $log_file"; main(); sub main { if (-e $file_01_txt) { # We are going to open the log file for appending. open($log_report, '>>', $log_file) or die "Cannot open $log_fi +le."; # We are going to open the HTML file for appending. open($html_report, '>>', $html_file) or die "Cannot open file +$html_file"; # If the file exists, we are going to open it, so we can read +from it. print $log_report "$file_01_txt has been found.\n"; open (my $fh, "<", $file_01_txt) or die "Cannot open file $fil +e_01_txt"; print $html_report "\n"; print $html_report "#### Now Analyzing '$file_01_txt'\n"; print $html_report "\n"; while (my $line = <$fh>) { chomp $line; if ($line =~ /search criteria 01/i) { print $html_report "$line\n"; } if ($line =~ /search criteria 02/i) { print $html_report "$line\n"; } if ($line =~ /search criteria 03/i) { print $html_report "$line\n"; print $html_report "\n"; } } close $log_report; close $html_report; } else { # We are going to open the log file for appending. open($log_report, '>>', $log_file) or die "Cannot open $log_fi +le."; # We are going to log that the file has not been found. print $log_report "$file_01_txt has not been found.\n"; close $log_report; } }
Is there a more clean way of opening, writing to, and closing the HTML and log files?
Right now, I have one "main" sub that holds all of the "if" statements for each file. Should I break those up into different subs?"
Thanks for any help you might be able to provide!
Nico
In reply to Perl File Parsing - My Code Works, but it's Ugly! by Nico
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |