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++;
}