【问题标题】:Split function using Text::CSV_XS使用 Text::CSV_XS 分割函数
【发布时间】: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

【问题讨论】:

    标签: regex perl csv


    【解决方案1】:

    简化您的正则表达式。您不需要.* (perldoc -f split)。 split 将点视为分隔符,因为它位于字符类方括号内。

    use warnings;
    use strict;
    use Data::Dumper;
    
    my $Line = '21a94551,00:00:59.643;ERROR;';
    my @fs = split /[,;]/, $Line;
    print Dumper(\@fs);
    
    __END__
    $VAR1 = [
              '21a94551',
              '00:00:59.643',
              'ERROR'
            ];
    

    【讨论】:

      【解决方案2】:

      [] 中的内容不是正则表达式,它是一组字符或字符范围或类。当您只想在 ,; 上拆分时,您已经告诉它拆分 ,.*;split /[,;]/, ...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        • 2013-01-24
        • 2013-06-02
        • 2018-10-29
        相关资源
        最近更新 更多