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

Monks - What is the standard module used to output a comma delimitted text file with each in double quotes? Please review the below code. Thanks, Dave
printf OUTPUTFILE $dataRow{field1} . "," . $dataRow{field2} . +"," . $dataRow{field3} . "," . $dataRow{field4} . "," . $dataRow{field5} . "\n";

Replies are listed 'Best First'.
Re: Database Output Comma Delimitted w/quotes
by ikegami (Patriarch) on Aug 27, 2008 at 00:03 UTC

    There's Text::CSV_XS with the always_quote option set.

    use Text::CSV_XS qw( ); my $csv = Text::CSV_XS->new({ always_quote => 1, }); while (...) { my %dataRow = ...; $csv->combine(@dataRow{qw( field1 field2 field3 field4 field5 )}) or die; print OUTPUTFILE $csv->string() or die; }
Re: Database Output Comma Delimitted w/quotes
by chromatic (Archbishop) on Aug 26, 2008 at 23:39 UTC

    join is a good start, but we'd have to know more about the contents of your hash to answer any better. In general, you should be careful to escape any double-quotes in your data. I'd use something like:

    print {$outfile} join ', ', map { qq|"$_"| } map { escape_quotes( $_ ) } @dataRow{qw( field1 field2 field3 field4 field5 ) }; ... sub escape_quotes { my $string = shift; # a negative-lookbehind may be appropriate # to prevent double-escaping $string = s/"/\\"/g; return $string; }
Re: Database Output Comma Delimitted w/quotes
by toolic (Bishop) on Aug 26, 2008 at 23:43 UTC
    Use qq to allow interpolation of variables and to print literal quotes. Is this what you had in mind?
    use strict; use warnings; my %dataRow = (field1=>1, field2=>2); print qq{$dataRow{field1}","$dataRow{field2}\n}; __END__ 1","2
      I just need the output in a simple comma delimmted file. See below. "COLOMON1","COLOMON2" "COLOMON1","COLOMON2" "COLOMON1","COLOMON2" "COLOMON1","COLOMON2" "COLOMON1","COLOMON2"
Re: Database Output Comma Delimitted w/quotes
by jethro (Monsignor) on Aug 26, 2008 at 23:41 UTC

    Don't think there is a module for that

    print OUTPUTFILE '"',join('","',@dataRow),'"' if (@dataRow); print "\n";

    UPDATE: Removed double if. Thanks Ikegami.

    2ND UPDATE: Also I seem to have missed that AnonMonk uses a hash for the rows. So I have to withdraw my solution and only comment that probably an array would have been better to store the fields