【发布时间】:2016-04-28 13:51:52
【问题描述】:
我正在解析一个文件 - 我要做的第一件事是将前三个字段连接起来,并将它们添加到每条记录的前面。然后我想擦洗任何冒号、单引号、双引号或反斜杠的数据。以下是我的做法,但有没有办法让我使用 $line 变量更有效?
# Read the lines one by one.
while($line = <$FH>) {
# split the fields, concatenate the first three fields,
# and add it to the beginning of each line in the file
chomp($line);
my @fields = split(/,/, $line);
unshift @fields, join '_', @fields[0..2];
# Scrub data of characters that cause scripting problems down the line.
$_ =~ s/:/ /g for @fields[0..39];
$_ =~ s/\'/ /g for @fields[0..39];
$_ =~ s/"/ /g for @fields[0..39];
$_ =~ s/\\/ /g for @fields[0..39];
【问题讨论】:
-
您可能应该在这里颠倒您的逻辑,即对于每个字段,应用所有这些替换。我认为这里的正确答案是你应该使用像
Text::CSV_XS这样的模块,然后你就不需要做任何卫生工作了。 -
它们不需要“可用”。你设法安装了你的脚本,所以你也可以设法安装那些称为模块的脚本。
-
要么你有权限在上面放 Perl 代码,要么你没有,所以你有足够的权限来安装 Perl 模块。
-
@BigRedEO You don't need root/admin privileges to install modules. 不使用模块会让你的生活变得更加困难。如果没有必要,不要重新发明轮子。
-
@HunterMcMillen: “你应该使用像 Text::CSV_XS 这样的模块,然后你就不需要做任何卫生工作了” 我希望这是真的,但是@ 987654325@ 经常被视为万灵药。 OP 正在从数据中删除单引号和双引号、冒号和反斜杠,并且该模块不会执行此类操作。偶尔会出现一个 CSV 文件,最好使用
Text::CSV进行解析,它通常是 Microsoft Excel 的输出。其余时间,一个简单的chomp后跟split /,/是更好的选择
标签: perl parsing data-scrubbing