Balakumar
Balakumar

Reputation: 650

Writing CSV in perl

I am parsing a html file and writing the source codes in separate cells by using the code:

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

where the variable $table contains the content below::

<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>"

which is making the CSV to occupy and overlapping the next cells. How can i make them to print in only one cell?

Update

@TLP Thanks but if i use this code

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;

its still showing an error as "Expected fields to be an array ref"

Update

Thanks SzG, I have another doubt how can i add a newline to it, i want to print it in row by row, if i use

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

its still not working as expected. i think i am wrong in some where

Upvotes: 2

Views: 9767

Answers (1)

SzG
SzG

Reputation: 12609

It was suspicious that you never used the opened $fh filehandle. And yes, csv_print needs a filehandle and an array-ref.

In your original code it seemed you wanted to append to an existing CSV file open(MYFILE ,">>Test.csv"). So I changed the new code that way as well.

$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;                                                               

Upvotes: 4

Related Questions