我是 Perl 的新手,但仍在试图弄清楚如何用这种语言编写代码。
我目前正在尝试将一长串 csv 拆分为多行。
数据示例
a,b,c<br />x,y,x<br />
到目前为止,我已经设法将其拆分,添加引号,以便稍后再次添加到 CSV 文件中:
"a,b,c""x,y,z"
通过使用引号,它只是表示哪些 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"
}