Writing CSV in perl



我正在使用代码解析一个 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"]); 

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

您从未使用过打开的$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;                                                               

最新更新