问题描述
我是编程新手,我想为perl中的以下函数编写代码。
在每个行格式如下的csv文件中,我有几个CSV文件(1.csv,2.csv,3.csv,4.csv ...)。
<time,id1,id2,id3,filename> :
202008110100,10819066580072,2147858602,Afile.txt
202008110110,12819066589761,AC987678,Bfile.txt
202008110120,8927489178,AC398761,Bfile.txt
202008110130,29274125780232,3829271910,AC119651,Cfile.txt
.
.
.
#id1,id3 might be blank sometimes.
我有这样的输入:
<starttime,endtime,id3>:
#id1,id3 might be **0**
eg):202008110105,202008110115,0
如果id1
,id2
,id3
= 0,则忽略该值,仅匹配非零的id
。
并在time
和starttime
期间提取endtime
。
我期望这样的匹配输出:
1.csv:Afile.txt
以下是我写的内容,但似乎有问题...有人可以帮助我吗?
my $dir = <C:/Windows/Users/USER/Documents/Perlprogram>;
@files = ("1.csv","2.csv,3.csv,4.csv");
foreach $file (@files) {
print "$file\n" if -f $file;
open(IN,"<./$file") or die("Error");
@before = <IN>;
close(IN);
@after = grep(/$greplist/,@before);
foreach $after (@after) {
print "$after\n";
}
sub after {
$time = $_[6];
if ($time >= $starttime and $time <=$endtime){
open(OUT,">>./search_result.txt");
print($file,$_[4]);
print(OUT $_[4]);
close(OUT);
}
}
解决方法
似乎有问题...
@files = ("1.csv","2.csv,3.csv,4.csv");
除语法外,第一个文件之后的文件名未正确引用。
正如北极熊所说,$greplist
未定义。假设将其设置为您称为 input 的内容,我们可以使用
($starttime,$endtime,$id1,$id2,$id3) = split ',',$greplist;
程序的其余部分有些不连贯;您可以将行@before = <IN>;
替换为
while (<IN>)
{
@_ = split ','; # split the CSV line to the values
print $_[4] if !$id1 || $_[1] == $id1
and !$id2 || $_[2] == $id2
and !$id3 || $_[3] == $id3
and $starttime <= $_[0]
and $_[0] <= $endtime
}
并删除foreach $file
循环的其他内容。