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

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
  • Comment on Re: Better Code Solution needed for the below CSV file parsing and printing in HTML format
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Better Code Solution needed for the below CSV file parsing and printing in HTML format
by binf-jw (Monk) on Oct 14, 2008 at 13:29 UTC
    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