in reply to csv output
With that function, supposing that $file was a file you wanted to write, @cols an array of columns that you wanted to put in a CSV file, and @data was an array of hash references with your data (see References Quick Reference if you don't know what an array of hash references is), you could write it as follows:# Takes an array and returns it as a CSV row sub format_csv { my @fields = @_; foreach (@fields) { if (not defined($_)) { $_ = ""; } elsif (0 == length($_)) { $_ = '""'; } elsif (/\s|"|'|,/) { s/"/""/g; $_ = qq("$_"); } } (join ",", @fields) . "\n"; }
Note that I have put in error checking as very wisely recommended in perlstyle...local *FILE; open (FILE, "> $file") or die "Cannot write '$file': $!"; print FILE format_csv(@cols); foreach my $row (@data) { print FILE format_csv(@$row{@cols}); } close(FILE) or die "Cannot close '$file': $!";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re (tilly) 1: csv output
by Juerd (Abbot) on Mar 14, 2002 at 19:25 UTC | |
by tilly (Archbishop) on Mar 14, 2002 at 19:53 UTC | |
by Juerd (Abbot) on Mar 14, 2002 at 20:09 UTC | |
by tilly (Archbishop) on Mar 14, 2002 at 20:27 UTC | |
by Juerd (Abbot) on Mar 14, 2002 at 21:21 UTC |