【发布时间】:2020-04-09 02:39:56
【问题描述】:
我正在尝试在 perl 中操作 csv。
输入 csv 在列数据中有一些换行符,导致其他外部程序失败。我在 Perl 脚本下面写了对 csv 进行预处理以删除这些字符。
use strict;
use warnings 'all';
# Using Text::CSV file to allow
# full CSV Reader and Writer
use Text::CSV;
use open ":std", ":encoding(UTF-8)";
my $file = $ARGV[0] or die;
my $csv = Text::CSV->new (
{
binary => 1,
auto_diag => 1,
sep_char => ', '
});
my $sum = 0;
# Reading the file
open(my $data, '<:encoding(utf8)', $file) or die;
while (my $words = $csv->getline($data))
{
tr/\r\n//d for @$words; #removing new lines
tr/,/;/ for @$words; #replacing comma with semicolon
$csv->combine(@$words);
print $csv->string, "\n";
}
# Checking for End-of-file
if (not $csv->eof)
{
$csv->error_diag();
}
close $data;
我使用下面的 shell 脚本作为包装器将修改后的文件存储在另一个 csv 中。下面的外壳包装器。
perl xyz.pl ${source_csv_file_name} > ${destination_processed_csv_file_name}
我希望我可以在 perl 脚本本身中使用 out csv 处理程序将输出写入另一个文件。我尝试了几种方法,但不断收到一个或其他错误。以下是我尝试过的。
my $outcsv = Text::CSV->new ( { binary => 1, quote_char => "", escape_char => "\\" } );
open(my $data, '<:encoding(utf8)', $file) or die;
open(my $fh, ">:encoding(utf8)", "new.csv") or die " new.csv: $!";
while (my $words = $csv->getline($data))
{
tr/\r\n//d for @$words;
tr/,/;/ for @$words;
$csv->combine(@$words);
# Open a handle to the file "new.csv"
$outcsv->print ($fh, $_) for @words;
#print $csv->string, "\n";
}
# Checking for End-of-file
if (not $csv->eof)
{
$csv->error_diag();
}
close $data;
close $fh or die "new.csv: $!";
问题是我在上面发布的第一个代码,但是为了编写我使用了 shell 包装器的文件。现在第二个 perl 脚本(我只发布了与第一个不同的代码),当我运行它时失败并出现错误。我了解该错误,但不确定如何修复它“全局符号@words 需要在 xyz.pl 第 29 行显示明确的包名称。由于编译错误,xyz.pl 的执行中止。 如果有人可以在这里提供帮助,我将不胜感激。
谢谢
【问题讨论】:
-
如果您在此处发布示例数据将不胜感激。
-
另外,告诉我们什么(以及如何)失败
-
好的,我发布的第一个代码有效,但是为了编写文件,我使用了 shell 包装器。现在第二个 perl 脚本(我只发布了与第一个不同的代码)当我运行它时失败并出现以下错误。我理解错误但不知道如何修复它“全局符号
@words requires explicit package name at d2l_preprocess_csv_files.pl line 29. Execution of d2l_preprocess_csv_files.pl aborted due to compilation errors. " -
好的,感谢您的回复。这种信息需要首先出现在问题中。 (例如:我马上发现你的第二个程序中有一个
@words——我想是发帖时的一个错字,你不小心把那个$丢了。但是一旦你显示错误,我们就知道 实际上是个问题。)