Kevman has asked for the wisdom of the Perl Monks concerning the following question:

I have a file which is comma delimited, that needs to
be read into arrays.

This would be easy with
#!/usr/local/bin/perl -w use strict; my $line; open (FH, "< ./kevtest.dat") || die "Couldn't open ./kevtest.dat: $!"; #Read in all the lines my @lines = <FH>; chomp @lines; for $line (@lines) { $line =~ s/\"//g; print STDERR "$line\n"; } #Close the file close FH || die "Couldn't ./fred.dat\n";
However, the file can contain

field 1, "field 2, has a comma", field 3
If I strip `"` then I will get 4 elements in @lines, not 3.

Help pls?

Kev

Replies are listed 'Best First'.
Re: Comma Delimited Problems
by arden (Curate) on Mar 09, 2004 at 14:55 UTC
      Thks for the quick responses all - I'll take a look in cpan

      Kev
Re: Comma Delimited Problems
by dragonchild (Archbishop) on Mar 09, 2004 at 14:57 UTC
    I'd recommend Text::xSV (written by our tilly), which solves some edge cases that Text::CSV misses, and allows any single-character separator to be used.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Comma Delimited Problems
by Tomte (Priest) on Mar 09, 2004 at 14:57 UTC

    I suggest Text::CSV or yet better under some circumstances DBD::CSV

    CVS is a very ugly wheel one usually does not want to reinvent :)

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: Comma Delimited Problems
by Happy-the-monk (Canon) on Mar 09, 2004 at 15:10 UTC
    If you can access the Perl Cookbook, there's a gleeful recipe at pages 44ff. Sören
Re: Comma Delimited Problems
by Abigail-II (Bishop) on Mar 09, 2004 at 15:25 UTC
    Untested:
    use Regexp::Common; /$RE{list}{-pat => "\\w+|$RE{quoted}"}/;

    Although this only matches the entire 'list', it doesn't capture the individual elements.

    Abigail