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

Hello, I am new to Perl and would just like to know if i can do the following. I would like to be able to populate a column in a CSV file from data that i will take from a external source. E.g First Column is node name and would like to populate, say, the last column which i have as my custom column. Many thanks for any help.

Update:
Thanks for the hasty replies. I will try and have a go. I think i should have started with Perl years ago as it seems a very useful programming language.

Edit by castaway - prepended original content

Replies are listed 'Best First'.
Re: Adding a field into CSV and populating
by ctilmes (Vicar) on Apr 18, 2004 at 11:04 UTC
    Sure, you can do that with Perl.

    What have you tried so far? Where are you having trouble?

    You might check out some of the CPAN CSV modules -- they may save you some programming effort.

Re: Adding a field into CSV and populating
by erniep (Sexton) on Apr 18, 2004 at 12:35 UTC
    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!!--
      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.