Hi bcarroll,

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.

To parse CSV file, you will want to use Text::CSV instead of parsing by hand using split function. Though that "may" do on some occasions but it's alot better using a tested module.

Though you didn't show how you want the output look like and which field that you are still having comma in. Using your dataset and going by the title of your post something like this works:

use warnings; use strict; use Text::CSV; my $csv = Text::CSV->new( { binary => 1 } ) or die Text::CSV->error_diag(); print "<Table border = 1 cellpadding = 1 callspacing = 1 width = 80% align = + 'center'>"; while ( my $row = $csv->getline( \*DATA ) ) { print "<tr>"; print "<td>$_</td>" for @$row; print "</tr>"; } print "</Table>"; __DATA__ 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
OUTPUT
SourceDestinationUserState
192.168.0.2192.168.0.6cn=user1,ou=infrastructure,ou=accounts,o=ORG,c=USAllowed
192.168.0.3192.168.0.6cn=user2,ou=infrastructure,ou=accounts,o=ORG,c=USDenied

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

In reply to Re: split on comma unless within quotes... by 2teez
in thread 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.