in reply to how to modify a field in a CSV file

#!/usr/bin/perl -w # Caveat: untested code. Don't do anything foolish with it. use strict; use Tie::File; tie my @ry,"Tie::File", "MyFile.csv" or die "MyFile.csv:$!"; my $i = 10; # or whatever my @j = split(",",$ry[$i]); $j[1] = "This is a fence"; $ry[$i] = join(",",@j); # #############################

Obviously you'd have to customize the above to suite your needs.


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: how to modify a field in a CSV file
by beerman (Novice) on Sep 02, 2011 at 17:57 UTC
    Peter, Thanks for the suggestion. My data is quite flexible and I only provided an example for illustrative purposes. My goal is to modify a field in a CSV file. The input to my script is the field (index) to modify and the change to the field. As previously mentioned, it is easy to parse a CSV file using text:csv_xs and get the field that the user wants to change and then make the change. My only problem is that I've not figured out how to write the new file with just the change to the field. In other words, I'm trying to retain the double quotes and the comma delimiters that were part of the input file. I'd like to think that I can do this with text::csv_xs but I've not figured out how to do it yet so that is the reason for this post
      I'm trying to retain the double quotes and the comma delimiters that were part of the input file. I'd like to think that I can do this with text::csv_xs

      Sure, see combine().

      my $csv = Text::CSV->new ( { quote_space => 0 } ) or die "Cannot use CSV: ".Text::CSV->error_diag (); my @columns = ("What, a nice day", "This is a fence", "Here is an,and +day"); print $csv->string() if $csv->combine(@columns);

      generates the following line:

      "What, a nice day",This is a fence,"Here is an,and day"
        That did it! Thank you so much for cluing me into to the combine function. You are great and the next beer I drink is in your honor!