Perl和Regex - 从.csv解析值

Zel*_*Elf 2 regex perl

我需要创建一个perl脚本来读取给定文件夹中的最后一个修改过的文件(该文件始终是.csv)并解析其列中的值,因此我可以将它们控制到mysql数据库.

主要问题是:我需要将日期与小时分开,国家与名称分开(CHN,DEU和JPN代表中国,德国和日本).

他们像下面的例子一样聚集在一起:

"02/12/2014 09:00:00","3600","1","CHN - NAME1","0%","0%"
"02/12/2014 09:00:00","3600","1","DEU - NAME2","10%","75.04%"
"02/12/2014 09:00:00","3600","1","JPN - NAME3","0%","100%"
Run Code Online (Sandbox Code Playgroud)

到目前为止,我可以拆分行,但是如何让它理解每个值进入""和分隔,应插入到我的数组中?

my %date;
my %hour;
my %country;
my %name;
my %percentage_one;
my %percentage_two;

# Selects lastest file in the given directory
my $files = File::DirList::list('/home/cvna/IN/SCRIPTS/zabbix/roaming/tratamento_IAS/GPRS_IN', 'M');
my $file = $files->[0]->[13];

open(CONFIG_FILE,$file);
while (<CONFIG_FILE>){
    # Splits the file into various lines
    @lines = split(/\n/,$_);
    # For each line that i get...
    foreach my $line (@lines){
        # I need to split the values between , without the ""
        # And separating Hour from Date, and Name from Country
        @aux = split(/......./,$line)
    }
}
close(CONFIG_FILE);
Run Code Online (Sandbox Code Playgroud)

cho*_*oba 5

readline<>只读一行.没有必要在换行符上拆分它.但是,使用Text :: CSV代替修复代码:

#!/usr/bin/perl
use 5.010;
use warnings;
use strict;

use Text::CSV;

my $csv = 'Text::CSV'->new({ binary => 1 }) or die 'Text::CSV'->error_diag;

while (my $row = $csv->getline(*DATA)) {
    my ($date, $time)    = split / /,   $row->[0];
    my ($country, $name) = split / - /, $row->[3];
    print "Date: $date\tTime: $time\tCountry: $country\tName: $name\n";
}

__DATA__
"02/12/2014 09:00:00","3600","1","CHN - NAME1","0%","0%"
"02/12/2014 09:00:00","3600","1","DEU - NAME2","10%","75.04%"
"02/12/2014 09:00:00","3600","1","JPN - NAME3","0%","100%"
Run Code Online (Sandbox Code Playgroud)