我是 Perl 新手,仍在尝试弄清楚如何用这种语言编写代码。
我目前正在尝试将一长串 csv 拆分为多行。
数据示例
a,b,c<br />x,y,x<br />
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经设法将其拆分,添加引号,以便稍后再次添加到 CSV 文件中:
"a,b,c""x,y,z"
Run Code Online (Sandbox Code Playgroud)
通过引号,它仅表示哪些 CSV 集是在一起的。
我遇到的问题是,当我尝试创建 CSV 文件并在字符串中传递数据时,出现错误
“无法对未定义的变量调用方法“解析”。
当我打印出我传入的字符串时,它被定义并保存数据。我希望这是一件简单的事情,但由于缺乏经验,我做错了。
我使用的 CSV 代码是:
use warnings;
use Text::CSV;
use Data::Dumper;
use constant debug => 0;
use Text::CSV;
print "Running CSV editor......\n";
#my $csv = Text::CSV->new({ sep_char => ',' });
my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";
my $fileextension = substr($file, -4);
#If the file is a CSV file then read in the file.
if ($fileextension =~ m/csv/i)
{
print "Reading and formating: $ARGV[0] \n";
open(my $data, '<', $file) or die "Could not open '$file' $!\n";
my @fields;
my $testline;
my $line;
while ($line = <$data>)
{
#Clears the white space at the end of the line.
chomp $line;
#Splits the line up and removes the <br />.
$testline = join "\" \" ", split qr{<br\s?/>}, $line;
#my $newStr = join $/, @lines;
#print $newStr;
my $q1 = "\"";
$testline = join "", $q1,$testline,$q1;
print "\n printing testline: \n $testline \n";
}
$input_string = $testline;
print "\n Testing input string line:\n $input_string";
if ($csv->parse ($input_string))
{
my @field = $csv->fields;
foreach my $col (0 .. $#field) {
my $quo = $csv->is_binary ($col) ? $csv->{quote_char} : "";
printf "%2d: %s%s%s\n", $col, $quo, $field[$col], $quo;#
}
}
else
{
print STDERR "parse () failed on argument: ",
$csv->error_input, "\n";
$csv->error_diag ();
}
#print $_,$/ for @lines;
print "\n Finished reading and formating: $ARGV[0] \n";
}else
{
print "Error: File is not a CSV file\n"
}
Run Code Online (Sandbox Code Playgroud)
你没有创建一个Text::CSV对象,但你尝试使用它。
“无法对未定义的变量调用方法“解析”
这意味着 your$csv不存在,因此它没有名为 的方法parse。Text::CSV只需首先在代码顶部所有行下方创建一个对象use。
my $csv = Text::CSV->new;
Run Code Online (Sandbox Code Playgroud)
请看一下 的 CPAN 文档Text::CSV。
另外,我有没有提到你应该这样做use strict?
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |