Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Better Code Solution needed for the below CSV file parsing and printing in HTML format

by valavanp (Curate)
on Oct 14, 2008 at 12:10 UTC ( [id://716963]=perlquestion: print w/replies, xml ) Need Help??

valavanp has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I wrote the following scripts for parsing the CSV and printing in an HTML format.
Method 1:
#!c:/perl/bin/perl use strict; use warnings; #opening the csv file my $caption=pop(@ARGV); open(FH,$caption) || die("Cannot open $caption file"); my($line,$id,$name,$age,@records,@out); @out="<HTML><HEAD><TITLE>CSV Output</TITLE></HEAD><body><table border= +1><tr><td>ID</td><td>NAME</td><td>AGE</td>"; #creating a new file for the html output and writing the header conten +t open(FH1,">output.html"); print FH1 @out; #splitting the comma separated values and writing it to the html file while($line=<FH>){ next if($line=~/^ID/); chomp($line); ($id,$name,$age)=split(/,/,$line); print FH1 "<tr><td>$id</td><td>$name</td><td>$age</td></tr>"; } print FH1 "</table>"; close FH1; close FH;
The CSV file is:
ID,NAME,AGE 1,JOHN,21 2,MARK,32 3,CATHY,21
The HTML output which i got is:
<HTML><HEAD><TITLE>CSV Output</TITLE></HEAD><body><table border=1><tr> +<td>ID</td><td>NAME</td><td>AGE</td><tr><td>1</td><td>Alex</td><td>24 +</td></tr><tr><td>2</td><td>Bret</td><td>21</td></tr><tr><td>3</td><t +d>Cathy</td><td>24</td></tr></table>
Method 2:
#!c:/perl/bin/perl use strict; use warnings; $\="\n"; my($caption,$line,@out,@rec,$x,@output); #opening the csv file $caption=pop(@ARGV); open(FH,$caption) || die("Cannot open $caption file"); #print '<table border cellspacing=0 cellpadding=5>'; #print '<caption>' . $caption . '</caption>'; @out="<HTML><HEAD><TITLE>CSV Output</TITLE></HEAD><body><table border +cellspacing=0 cellpadding=5><caption>$caption</caption>"; open(FH1,">gen_try.html"); print FH1 @out; while($line=<FH>){ chomp($line) ; @rec = split(/,/, $line); $x=0; print '<tr>'; while($x <= $#rec){ print FH1 "\t <td>". $rec[$x] . '</td>'; ++$x; } print '</tr>'; } print '</table>';

When you compare both the methods, in the second method i didn't hard code the column headings directly in my script. But the html output which i am getting is not like as method1. Could you please any one suggest me a solution in which it should be generic not like method1. Please suggest me without using any modules like Text::CSV. I need the solution with out using modules.

Replies are listed 'Best First'.
Re: Better Code Solution needed for the below CSV file parsing and printing in HTML format
by jethro (Monsignor) on Oct 14, 2008 at 13:00 UTC

    You get different output because you forgot to add FH1 to some of the print statements in the second script

    By the way, the loop could be written like this:

    foreach (@rec) { print FH1 "\t <td>". $_ . '</td>'; }

    Better to read and less error prone (as long as you don't want to add or delete to the array inside the loop)

Re: Better Code Solution needed for the below CSV file parsing and printing in HTML format
by ww (Archbishop) on Oct 14, 2008 at 13:06 UTC
    Unless this is homework, there are only rare occasions when "with out (sic) using modules" is a valid reason for eschewing tried and tested means of solving your problem.

    Moreover, if you look closely at the .html output you posted, you'll note that it's NOT valid:

    ...<table order=1> <tr> <td>ID</td> <td>NAME</td> <td>AGE</td> # </tr> missing here <tr> <td>1</td> <td>Alex</td> ...

    NOR do I see any ready explanation of how your code(1) could have produced this output. Did you cut and paste accurately? And what, in your view, causes the second to fail as it does? That may (update: already answered by jethro) help you ascertain your problem without further coaching.

    Finally, perhaps you can explain what you mean by "...it should be generic not like method1."

Re: Better Code Solution needed for the below CSV file parsing and printing in HTML format
by Anonymous Monk on Oct 14, 2008 at 13:27 UTC
    Here's a neater version for you:
    use strict; use warnings; use English; $OUTPUT_RECORD_SEPARATOR = "\n"; # Open files my $csv_filename = shift; open my $csv_fh, "<", $csv_filename or die "Cannot open $csv_filenam +e file: ", $OS_ERROR; open my $html_fh, '>', 'gen_try.html' or die "Cannot open gen_try.html + file: ", $OS_ERROR; # Print Heading html using heredoc print {$html_fh} <<EOHTML; <HTML> <HEAD> <TITLE>CSV Output</TITLE> </HEAD> <body> <table border=1 cellspacing=0 cellpadding=5> <caption>$csv_filename</caption> EOHTML # Read CSV file while ( my $line = <$csv_fh> ) { chomp $line; # Only for html readability my @fields = split /,/, $line; print {$html_fh} ( '<tr>', ( map {qq{<td>$_</td>}} @fields ), '</t +r>' ) or die "Cannot print to html file: ", $OS_ERROR; } print {$html_fh} <<EOHTML; </table> </HTML> EOHTML close $csv_fh or die "Cannot close $csv_filename file: ", $OS_ERROR; close $html_fh or die "Cannot close output file: ", $OS_ERROR; __END__


    Or to make it a bit more compact

    use strict; use warnings; use English; $OUTPUT_RECORD_SEPARATOR = "\n"; # Open files my $csv_filename = shift; open my $csv_fh, "<", $csv_filename or die "Cannot open $csv_filenam +e file: ", $OS_ERROR; open my $html_fh, '>', 'gen_try.html' or die "Cannot open gen_try.html + file: ", $OS_ERROR; # Print Heading html using heredoc print {$html_fh} q{<HTML><HEAD><TITLE>CSV Output</TITLE></HEAD><body>< +table border=1 cellspacing=0 cellpadding=5><caption>$csv_filename</ca +ption>}; # Read CSV file while ( my $line = <$csv_fh> ) { chomp $line; # Only for html readability print {$html_fh} ( '<tr>', ( map {qq{<td>$_</td>}} ( split /,/, $l +ine ) ), '</tr>' ) or die "Cannot print to html file: ", $OS_ERROR; } print {$html_fh} q{</table></HTML>}; close $csv_fh or die "Cannot close $csv_filename file: ", $OS_ERROR; close $html_fh or die "Cannot close output file: ", $OS_ERROR; __END__


    Ahhhh much better...
    Although the map still looks a bit icky
    John
      Opps forgot to log in, Best bet for reading that is with a wide screen. I always forget that it gets compacted if the lines are too long. Sorry. - John

        Run your code through Perl::Tidy for all sorts of reformatting goodness.


        Perl reduces RSI - it saves typing

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://716963]
Approved by Corion
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-28 17:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found