in reply to Adding a field into CSV and populating

There are 10,000 ways to do something like this in perl... Here is a simple snippet that will modfiy a line in an array and then write it to an output file.
$filein=yourcvsfile.txt; $fileout=yourcvsfileout.txt; ####read into array open (FILEIN,"$filein") || die "Can't Open file : $!\n"; @mydata=<FILEIN>; close FILEIN; ####open output file open (FILEOUT,">$fileout") || die "1Can't Open b: $!\n"; foreach $mydata (@mydata) {($newfield1,$newfield2,$newfield3,$newfield +4,$newfield5) = split(',',$newline); if ($newfield1 eq $newvar) {$field1=$var1; ###preform sub routine to write &writenew}; sub writenew { $newfield1=$var2; $newfield2=$var2 $newfield3=$var2 $newfield4=$var2 $newfield5="anydata"; $mydata="$newfield1,$newfield2,$newfield3,$newfield4,$newfield5; " print FILEOUT $mydata; }
This may not be exact but it will give you a start--hopefully!!--

Replies are listed 'Best First'.
Re: Re: Adding a field into CSV and populating
by jZed (Prior) on Apr 18, 2004 at 16:21 UTC
    That solution will only work if the data contains no commas or newlines. For a real solution, use Text::CSV_XS or Text::xSV or use DBD::CSV which will additionally handle all of the file locking/opening/closing etc.

    It's unclear to me what the OP is asking, but my first interpretation was that he/she is asking not how to insert a *record* as you showed, but how to insert a *field*. If the OP means by that that they want to take an existing CSV file with, say 3 fields and turn it into a table with 4 fields and then populate the fourth field, then none of the modules do that explicitly. One way to do it (assuming the original CSV file uses the first line as column names) would be to manually add the field into the file (e.g. if the top line of the file is "col1,col2,col3" ... just edit it to be "col1,col2,col3,col4", then save the file and use one of the modules to populate the col4 field.