2

我正在解析一个 html 文件并使用以下代码在单独的单元格中编写源代码:

open(MYFILE ,">>Test.csv");
print MYFILE qq|"$name","$table","$picture"\n|;
close MYFILE;

其中变量 $table 包含以下内容::

<table cellspacing=0" cellpadding="0" style="text-align: center;">
<tbody>
<tr>
<td valign="middle" class="td1">
<p class="p1"><span class="s1"><b><i><u><font size="5">Brand New in Package 64 GB Black/Silver USB 2.0 Flash Drive</font></u></i></b></span></p>
<ul class="ul1">
<li class="li2">Do not be fooled by the low price! The flash drives are EXCELLENT quality and I can assure you that you will be more than pleased</li><li class="li2">True Capacity</li>
<li class="li2">&nbsp;I am the fastest seller you will find and having your item shipped to you as fast as possible is my first priority</li>
<li class="li2">Most purchases will be shipped within 24 hours if ordered Monday - Friday</li>
<li class="li2">If you have any questions please feel free to ask!</li></ul></td></tr></tbody></table><center><br></center><center><br></center><center><font size="7" color="#00429a">Need more space? Check out my 128 GB Listings for as low as </font><font size="7" color="#ad001f"><b><u>$33.99</u></b></font><font size="7" color="#00429a">!!</font></center><p></p>"

这使 CSV 占据并重叠下一个单元格。我怎样才能让它们只在一个单元格中打印?

更新

@TLP 谢谢,但如果我使用此代码

my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $fh, ">:encoding(utf8)", "Test.csv" or die "Test.csv: $!";
$csv->print ($name,$table);
close $fh;

它仍然显示错误为“预期字段是数组引用”

更新

谢谢SzG,我还有一个疑问,我该如何添加换行符,如果我使用,我想逐行打印

$csv->print($fh,["\n"]); 

它仍然没有按预期工作。我想我在某些地方错了

4

1 回答 1

4

怀疑您从未使用过打开的 $fh 文件句柄。是的,csv_print 需要一个文件句柄和一个数组引用。

在您的原始代码中,您似乎想附加到现有的 CSV 文件open(MYFILE ,">>Test.csv")。所以我也以这种方式更改了新代码。

$csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();                      
open $fh, ">>:encoding(utf8)", "Test.csv" or die "Test.csv: $!";         
$csv->print($fh, [$name, $table]);                                       
close $fh;                                                               
于 2013-09-16T13:51:17.310 回答