gpt4 book ai didi

regex - Perl 和 Regex - 从 .csv 解析值

转载 作者:行者123 更新时间:2023-12-02 08:30:33 36 4
gpt4 key购买 nike

我需要创建一个 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%"

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

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);

最佳答案

readline<>只读一行。没必要 split它在换行符上。但是,不要修复您的代码,而是使用 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%"

关于regex - Perl 和 Regex - 从 .csv 解析值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27251105/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com