【问题标题】:Perl syntax error without explanation while opening file to manage data打开文件以管理数据时出现 Perl 语法错误,没有解释
【发布时间】:2018-03-25 00:13:10
【问题描述】:

我正在尝试检查一个非常大的 CSV 文件以查找每列的所有唯一字符串。例如:

John
John
John
Mark

应该返回JohnMark

我无法弄清楚我的代码有什么问题。错误消息也没有帮助(特别是第 3 和第 4 个错误):

“my”变量@found 掩盖了 getdata.pl 第 66 行相同范围内的早期声明。
“我的”变量 $answer 掩盖了 getdata.pl 第 67 行同一语句中的早期声明。
getdata.pl 第 55 行的语法错误,靠近“){”
全局符号“@master_fields”在 getdata.pl 第 58 行需要明确的包名称(您是否忘记声明“my @master_fields”?)。
getdata.pl 第 61 行的语法错误,靠近“} else”

有人能指出我正确的方向吗?

这是我的代码:

# open file
open my $lines, '<', 'data.csv' or die "Unable to open data.csv\n";
my @records = <$lines>;
close $lines or die "Unable to close data.csv\n";   # 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_records\n";
    }
}

【问题讨论】:

  • 您使用的是哪个版本的 Perl?
  • 您在此行缺少另一个结束 )
  • Serge 识别的语法错误(if 中缺少右括号),“每列所有唯一字符串”是什么意思?您的代码在第一列中查找唯一字符串。

标签: perl file


【解决方案1】:
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]\E\z/, @found )

或者更好,

grep( $_ eq $master_fields[0], @found )

最后,你滥用了 CSV 解析器——让它通过使用 getline 而不是换行符来确定记录的结束位置——而且你的效率非常低——O(N2 ) 而不是 O(N)——使用数组而不是哈希。

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;

【讨论】:

  • 救命稻草!谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 1970-01-01
  • 2019-08-01
  • 2018-05-03
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多