tw has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks,
I am after some advice on how to read a csv file using Text::CSV_XS from line X into an array. The csv files i am working with have an unusual header so if i try to read the header an error is returned.
I can read a normal csv file with the code below, starting from line 42 in this case -- the code is essentially from CSV_XS synopsis with a few modifications.
#!/usr/bin/perl -w #use strict; #use warnings; #use diagnostics; use Text::CSV_XS; my $file = 'test.csv'; #csv file name my @rows; # array that will store csv values my $csv = Text::CSV_XS->new ({ binary => 1 }) or die "Cannot use CSV: ".Text::CSV->error_diag (); #open file open my $FH, "<:encoding(utf8)", "$file" or die "$file: $!"; #read file in while loop my $i = 1; while (my $row = $csv->getline ($FH) ) { if ($i > 42) {push @rows, $row;} $i++ } $csv->eof or $csv->error_diag (); #close file close $FH; #print contents of @rows array for my $print_rows (@rows) { print "@$print_rows\n"; }
I tried replacing getline with getline_all but i'm new to perl and not certain of the syntax or if it will even work as i expect. Or is a different loop set-up possible so the initial lines won't be parsed.
Thanks for any advice
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Text::CSV_XS read file from line X
by GrandFather (Saint) on Jan 04, 2011 at 07:26 UTC | |
by tw (Acolyte) on Jan 04, 2011 at 07:57 UTC | |
|
Re: Text::CSV_XS read from line X
by Tux (Canon) on Jan 04, 2011 at 07:03 UTC | |
by tw (Acolyte) on Jan 04, 2011 at 07:26 UTC | |
by Tux (Canon) on Jan 04, 2011 at 07:51 UTC | |
by tw (Acolyte) on Jan 04, 2011 at 09:09 UTC | |
by Tux (Canon) on Jan 04, 2011 at 11:48 UTC | |
by GrandFather (Saint) on Jan 04, 2011 at 07:29 UTC |