I have the following Perl,
open (FILE, 'file.htm');
my $tree = HTML::TreeBuilder->new_from_content(do { local $/; <FILE> });
for ( $tree->look_down( 'class' => 'postbody' ) )
{
my $location = $_->look_down( 'class' => 'posthilit' )->as_trimmed_text;
my $comment = $_->look_down( 'class' => 'content' )->as_trimmed_text;
my $name = $_->look_down( '_tag' => 'h3' )->as_text;
$name =~ s/^Re:\s*//; $name =~ s/\s*$location\s*$//;
print "Name: $name\nLives in: $location\nCommented: $comment\n";
my $csv = Text::CSV->new();
$csv->column_names('field1', 'field2', 'field3');
$csv->print ($fh, [$name,$location,$comment]);
open $fh, ">", "file.csv" or die "ERROR: $!";
close $fh or die "$!";
}
This only outputs one line from the input file into the new ‘file.csv’ file.
How can I get it to put all the results into the results file.
Thanks in advance.
The code as written only prints one line because you only call
$csv->printonce. Since you obviously have more than one line of data, you need to create a loop that prints all of the lines. Something like this:I can’t give you any more detailed answer than this without seeing the rest of your code and knowing how the variables
$name, $location, $commentare assigned.Update after the question was edited:
You have a loop with
for ($tree->look_down(...)), which is fine and takes the place of thewhileloop that I described above. However, as currently written, you’re making a new$csvobject and a new file every time through the loop! That’s why you only every get one line in the output file. You need to take the following lines and put them before the beginning of theforloop:Inside the loop you only need to do this:
Then once the loop has completed, you can do this: