
#   Parse fields in a CSV-format file and return an array of field values

#   @fields = &csv($CSV_record);

#   Only double quoted fields are currently recognised as permitting
#   embedded commas.

#                           by John Walker
#                      http://www.fourmilab.ch/
#                            August 1998

#               This software is in the public domain.

    sub csv {
        package csv;
        local($l) = @_;
        local($f, @fields);

        while (1) {
            if ($l =~ s/^\s*"(([^"\\]|\\.)*)"\s*//) {
                $f = $1;
            } else {
                $l =~ s/^\s*([^,]*)//;
                $f = $1;
                $f =~ s/\s+$//;
            }
            push(@fields, $f);
            if ($l !~ s/\s*,//) {
                last;
            }
        }
        @fields;
    }

    1;
