【问题标题】:Perl string parsing codePerl 字符串解析代码
【发布时间】:2013-06-22 23:18:38
【问题描述】:

我想知道是否有人可以帮助我更好地理解解析文本文件的给定代码在做什么。

  while ($line = <STDIN>) {
    @flds = split("\t", $line);
    foreach $fld (@flds) {
        if ($fld =~ s/^"(.*)"$/\1/) {
            $fld =~ s/""/"/g;
        }
    }
    print join("\t", @flds), "\n";
}

我们将这段代码作为解析文本文件的开始。

Name    Problem #1  Comments for P1 E.C. Problem    Comments    Email
Park, John  17  Really bad. 5       park@gmail.edu
Doe, Jane   100 Well done!  0   Why didn't you do this? doe2@gmail.edu
Smith, Bob  0       0       smith9999@gmail.com

...这将用于根据解析的文本设置格式化输出。

我无法完全理解代码块如何解析和保存信息,以便知道如何访问我想要的信息的某些部分。有人能更好地解释一下上面的代码在每一步都在做什么吗?

【问题讨论】:

    标签: string perl parsing text


    【解决方案1】:

    这实际上看起来是一种非常糟糕的解析 CSV 文件的方法。

    while ($line = <STDIN>) { #read from STDIN 1 line at a time.
        @flds = split("\t", $line);  #Split the line into an array using the tab character and assign to @flds
        foreach $fld (@flds) {  #Loop through each item/column that's in the array @fld and assign the value to $fld
            if ($fld =~ s/^"(.*)"$/\1/) {  #Does the column have a string that is surrounded in quotes?  If it does,  replace it with the string only.
                $fld =~ s/""/"/g; #Replace any strings that are only two double quotes.
            }
        }
        print join("\t", @flds), "\n";  #Join the string back together using the tab character and print it out.  Append a line break at the end.
    }
    

    【讨论】:

    • 谢谢,所以这段代码只是改变了一些文本的格式,然后用制表符分隔的值重新连接起来,对吗?
    • 最好将解释放在代码外部而不是在代码内部注释
    猜你喜欢
    • 2014-07-19
    • 2021-06-17
    • 2015-03-11
    • 2013-02-04
    • 2019-05-07
    • 2011-01-08
    • 2011-11-26
    • 2017-11-10
    • 1970-01-01
    相关资源
    最近更新 更多