Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

create CSV from an array

Status
Not open for further replies.

mutasie

Programmer
Aug 23, 2009
6
US
Another newbie question:

From an array, how do I generate a CSV? I use a foreach loop, but it will add an extra "," after the last number, as the example below:


my @array = (1,2,3,4,5);

foreach my $num (@array){
print $num = $num . ",";
}

output:1,2,3,4,5,

How should I approach this? Thanks.

Allen
 
Or alternatively use Text::CSV_XS
Perl:
use strict;
use warnings;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new();
my @array = (1,2,3,4,5);

$csv->combine(@array);
my $csvLine = $csv->string();
print $csvLine, "\n";
CSV files are more tricky than they first appear - using the module to parse, read, and write them takes out all of the pain, especially if your data has embedded commas, quotes, and apostrophes...





Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Both answers are relevant and valid.
In such a simple case I'd probably just use join:
Code:
print join(',', @array), "\n";
As Steve rightly points out though, if this code is likely to grow and you are planning to use more complicated data (that might, for example, contain quotes in the data) then you really should use a module to do the work for you.
Your original code worries me though as I suspect you are actually altering your original data in the @array.

The code:
Code:
$num = $num . ",";
assigns a new value to $num in each case. The scary thing is that "foreach" creates an alias to each element so by altering $num you would actually be altering each element of the array. If you needed to re-use it later in your code it would be completely corrupted.

HTH


Trojan.
 
Ah... I didn't even think about that. Thank you so much for pointing that out.

I appreciate everyone's help on this!

Allen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top