Joma has asked for the wisdom of the Perl Monks concerning the following question:
Recently became involved with Regular Expressions and, while experimenting with Perl scripts using Text::ParseWords, I came up with a script containing the following code: I read a file with the CSV text line: "earth",1,,"moon",9.374
use Text::ParseWords; @fields = (); my $file = $ARGV[0] or die "Missing CSV file on the command line\n"; open($text, '<', $file) or die "Could not open '$file' $!\n"; $line = <$text>; @fields = quotewords(',', 0, $line); foreach $field (0..$#fields) { print $field + 1 . " $fields[$field]\n"; }
#------------------------------------ The above works fine and prints: 1 earth 2 1 3 4 moon 5 9.374 #=================================================================== However, if I try the following,
my $file = $ARGV[0] or die "Missing CSV file on the command line\n"; open($text, '<', $file) or die "Could not open '$file' $!\n"; while ($line = <$text>) { @fields = quotewords(',', 0, $line); } foreach $field (0..$#fields) { print $field + 1 . " $fields[$field]\n"; }
it only prints: 1 What am I missing here?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Parsing CSV file
by Tux (Canon) on Jul 05, 2016 at 07:07 UTC | |
|
Re: Parsing CSV file
by Athanasius (Archbishop) on Jul 05, 2016 at 04:28 UTC | |
by Joma (Initiate) on Jul 06, 2016 at 18:31 UTC | |
by Athanasius (Archbishop) on Jul 07, 2016 at 10:35 UTC | |
by choroba (Cardinal) on Jul 07, 2016 at 12:26 UTC | |
|
Re: Parsing CSV file
by genio (Beadle) on Jul 05, 2016 at 01:31 UTC | |
by Joma (Initiate) on Jul 05, 2016 at 14:07 UTC | |
|
Re: Parsing CSV file
by duyet (Friar) on Jul 05, 2016 at 06:14 UTC | |
|
Re: Parsing CSV file
by genio (Beadle) on Jul 05, 2016 at 01:33 UTC |