Click here to Skip to main content
15,886,578 members

Get results to write to CSV using Perl

LamboLambo asked:

Open original thread
The following Perl script cureently reads in an html file and strips off what I don't need. It also opens up a csv document which is blank.
My problem being is I want to import the stripped down results into the CSV's 3 fields using Name as field 1, Lives in as field 2 and commented as field 3.
The results are getting displayed in the cmd prompt but not in the CSV.

use warnings; 
use strict;  
use DBI;
use HTML::TreeBuilder;  
use Text::CSV;
open (FILE, 'punter.htm'); 
#open (my $fh, ">punter.csv") || die "couldn't open the file!";

 my $csv = Text::CSV->new (); 
 
$csv->column_names('field1', 'field2', 'field3'); 
open my $fh, ">", "punter.csv" or die "new.csv $!"; 
while ( my $l = $csv->getline_hr(my $fh)) { 
    next if ($l->{'field1'} =~ /xxx/); 
    printf "Field1: %s Field2: %s Field3: %s\n", $l->{'field1'}, $l->{'field2'}, $1->{'field3'}; 
$csv->print (my $fh, [my $name, my $location, my $comment]);
} 
close my $fh1 or die "$!"; 
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"; } 


An example of the html is -
<pre lang="xml"><div class="postbody"> <h3><a href "foo">Re: John Smith <span class="posthilit">England</span></a></h3> <div class="content">Is C# better than Visula Basic?</div> </div>



How can I get the results into a CSV?
Tags: Perl, HTML, CSV

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900