In Perl, how can I parse a CSV file where the fields contain comma separated values? -


there csv file called file.csv this: (this example)

"name","alias","phone","email","address" "rob","rob","534235","rob@example.com","us,uk" "nik","nik","976784","nik@example.com,nik@foram.org","uk" "picy","pic","327654,823747","pic@example.com","us" 

in file there 5 headers values more few headers. header can have number of values means more 2 or 3.

i trying output this:

name    nickname    phone        email                          address rob     rob         534235       rob@example.com                us,uk nik     nik         976784       nik@example.com,nik@foram.org  uk picy    pic         327654,823747   pic@example.com             

or specific column, column data above.

i know split function , limit in spliting:

while (<$fh>) {     @data = split /,/, $_, 5; } 

but not working here.

how can achieve this? idea?

with updated information, solution problem trivial:

#!/usr/bin/env perl  use strict; use warnings;  use text::csv_xs; use text::table::tiny;  $csv = text::csv_xs->new;  @data = ( $csv->getline(\*data) ); #header  while (my $row = $csv->getline(\*data)) {     next unless @$row == @{ $data[0] };     push @data, $row; }  print text::table::tiny::table(     rows => \@data,     header_row => 1, );  __data__ "name","alias","phone","email","address" "rob","rob","534235","rob@example.com","us,uk" "nik","nik","976784","nik@example.com,nik@foram.org","uk" "picy","pic","327654,823747","pic@example.com","us" 

output:

+------+-------+---------------+-------------------------------+---------+ | name | alias | phone         | email                         | address | +------+-------+---------------+-------------------------------+---------+ | rob  | rob   | 534235        | rob@example.com               | us,uk   | | nik  | nik   | 976784        | nik@example.com,nik@foram.org | uk      | | picy | pic   | 327654,823747 | pic@example.com               |      | +------+-------+---------------+-------------------------------+---------+

you create nested data structure parsing both each line, , fields in each line using csv parser:

while (my $row = $csv->getline(\*data)) {     next unless @$row == @{ $data[0] };     push @data, [         map [ $csv->parse($_) ? $csv->fields : () ], @$row     ]; } 

this useful if main interest in processing data, not printing out.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -