【发布时间】:2014-09-13 16:32:44
【问题描述】:
我正在尝试解析日志文件并将它们转换为 .csv 文件。我在拆分功能时遇到问题。例如,我在日志文件中有以下内容: 21a94551,00:00:59.643;ERROR; 。当我尝试拆分逗号 (,) 和分号 (;) 时,我在输出 csv 文件中的时间戳中丢失了 .643。我想保持时间(00:00:59.643)不变。我在日志文件中有多行(都有不同的数字),所以这些值不是明确的。
当我在拆分功能后使用打印功能时,值可以输出到屏幕上,但在 CSV 文件中
我是 Perl 的新手。有人可以解释我做错了什么吗?我认为问题可能在于如何处理字符串?
use strict;
use Cwd;
use Excel::Writer::XLSX;
use Text::CSV_XS;
use Spreadsheet::Read;
my $dirname = getcwd; # Set the directory to current working directory.
opendir (DIR, $dirname) || die; # Open the current directory
my @FileNameList = readdir(DIR); # Load the names of files in to an array
foreach (@FileNameList) #Read each of the file names
{
my $FileName = $_;
my $Output;
if ($FileName =~ m/iusp_\d+.log/)
{
print ("\n". $FileName." \n Correct Log File Found");
open (my $file, "<", $FileName);
while (<$file>) {
chomp; # Remove the \n from the last field
my $Line = $_; # Create the variable SLine and place the contents of the current line there
if ( $Line =~ m/ERROR/ ) # Select any line that has "ERROR" inside it.
{
my @fields = split /[,;]/, $Line; # Split up the line $Line by ", ;"
my $csv = Text::CSV_XS->new(); # Create new CSV
$csv->combine(@fields);
my $csvLine = $csv->string();
print $csvLine, "\n";
{
$Output = $csvLine . "\n";
}
my $OutputFileName = $FileName . ".csv";
print( "\n Saving File:" . $OutputFileName );
open( MyOutputFile, ">>$OutputFileName" );
print MyOutputFile $Output;
} #End of IF Statement
} #End of while statement
【问题讨论】: