The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

MusicRoom::Text::CSV - Comma seperated files

DESCRIPTION

Read and write text files in a particular format

FORMAT

For the purposes of this module a CSV file looks like this:

    artist,name,year
    "Elvis Costello","Alison","1977"
    "Riuichi Sakamoto","23rd Psalm","1983"
    "Duane Eddy","Forty Miles of Bad Road","1959"

In particular the first line has the names of the attribites then each following line has a data entry. Multi-line entries can be dealt with provided they are quoted

scan($fh,%flags)

A routine that reads in CSV data from an IO filehandle. The standard way to use this function is like:

    use MusicRoom::Text::CSV;

    my $fh = IO::File->new("source.csv");
    MusicRoom::Text::CSV::scan($fh,action => \&process_entry);

    sub process_entry
      {
        my(%attribs) = @_;

        my $this_artist = $attribs{artist};
        my $this_name = $attribs{name};

        print "Next entry is $this_artist \"$this_name\"\n";
      }

The valid flags are:

    action: A routine to call for each line
    carp_msg: A routine to call to report problems
    allowed: List of attributes that are allowed
    required: List of attributes required
    required_quiet: List of attributes required

The allowed and required flags need either an array of hash reference, for example:

    MusicRoom::Text::CSV::scan($fh,action => \&process_entry,
                        required => ["name"]);

The required_quiet flag tells the routine that we require a group of columns to be present before proceeding, but that if they are missing we just want to fail silently. This is a good option if you want to process a bunch of CSV files some of which have the data you need but you don't know in advance which ones, a call like:

    MusicRoom::Text::CSV::scan($fh,action => \&process_entry,
                        required_quiet => ["id","format"]);

will silently skip over the CSV file if it does not have both a "format" and "id" column.

scan($fh,$cols_ref,$flags_ref,%data)

Output data to a CSV file. Here is an example:

    my @to_columns = ("year","name");

    my @order;
    foreach my $id (sort by_year keys %local_data)
      {
        push @order,$id;
      }
    my $fh = IO::File->new(">$target_file");
    MusicRoom::Text::CSV::write($fh,\@to_columns,
                     {order => \@order, replace => 's/\~\|/, /g'},
                     %local_data);

The flags are:

    sort_fun: A function to call to sort entries
    order: Array of keys selecting the entries
    replace: A rexeg pattern to apply before outputting