I am trying to parse a CSV file into an HTML table, but I am running into an issue where one of the fields contains commas.

I am thinking I may need to use a different regular expression in the split statement, but wanted to check to see if anyone had a better approach.

Sample CSV:

Source,Destination,User,State 192.168.0.2,192.168.0.6,"cn=user1,ou=infrastructure,ou=accounts,o=ORG, +c=US",Allowed 192.168.0.3,192.168.0.6,"cn=user2,ou=infrastructure,ou=accounts,o=ORG, +c=US",Denied

This is what I have put together so far...

#!/usr/bin/perl use warnings; use strict; my $lineNum=1; print "<table>\n"; if ( -f $ARGV[0] ){ #$ARGV[0] is a file open(CSV,'<',$ARGV[0]); while (<CSV>){ csvLine2Html($_); } close(CSV); } else { #TODO... #$ARGV[0] is not a file } print "</table>\n"; sub csvLine2Html{ my $line = shift; chomp($line); if ($lineNum == 1){ #first line contains header information print "\t<tr>\n"; print map{ "\t\t<th>$_</th>\n" } split /,/, $line; print "\t</tr>\n"; } else { print "\t<tr>\n"; print map{ "\t\t<td>$_</td>\n" } split /,/, $line; print "\t</tr>\n"; } $lineNum++; }

In reply to split on comma unless within quotes... by bcarroll

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.