我正在尝试浏览一个非常大的CSV文件,以找到每个列的所有唯一字符串。例如:
John
John
John
Mark
应返回John
和Mark
。
我无法弄清楚我的代码问题是什么。错误消息也无济于事(特别是第三和第4个错误(:
"我的"变量@found masks在getdata.pl line 66中以同一范围声明。
"我的"变量$答案蒙版在getData.pl Line 67中的同一语句中声明。
getData.pl第55行的语法错误,附近"({"
全局符号" @master_fields"需要明确的软件包名称(您忘记了在getdata.pl行58.
getData.pl第61号线的语法错误,附近"} else"
有人可以将我指向正确的方向吗?
这是我拥有的代码:
# open file
open my $lines, '<', 'data.csv' or die "Unable to open data.csvn";
my @records = <$lines>;
close $lines or die "Unable to close data.csvn"; # Close the input file
# iterate through each line
foreach my $line ( @records ) {
if ( $csv->parse($line) ) {
my @master_fields = $csv->fields();
# if the string is already in the @found array, go to next line.
if ( grep( /^$master_fields[0]$/, @found ) {
next;
}
else {
# else; add to the @found array
push @found, $master_fields[0];
}
}
else {
warn "Line/record could not be parsed: @yob_recordsn";
}
}
if ( grep( /^$master_fields[0]$/, @found ){
应该是
if ( grep( /^$master_fields[0]$/, @found ) ){
由于 $master_fields[0]
不包含正则表达式,因此您需要将其转换为正则模式。
grep( /^$master_fields[0]$/, @found )
应该是
grep( /^Q$master_fields[0]E$/, @found )
由于您想与$master_fields[0]
进行完美匹配,
grep( /^Q$master_fields[0]E$/, @found )
应该是
grep( /^Q$master_fields[0]Ez/, @found )
或更好,
grep( $_ eq $master_fields[0], @found )
最后,您正在滥用CSV Parser&mdash;让它确定记录通过使用getline
而不是在Newlines上分开的结尾。而且您的效率极低(N 2 (,而不是O(n(&mdash;通过使用数组而不是哈希。
my $csv = Text::CSV_XS->new({ binary => 1, auto_diag => 2 }); # Or Text::CSV
my $qfn = 'data.csv';
open(my $fh, '<', $qfn)
or die("Unable to open "$qfn": $!n");
my %found;
while ( my $row = $csv->getline($fh) ) {
++$found{ $row->[0] };
}
my @found = sort keys %found;