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

Hi i want you to know that this question is crossposted on stackoverflow for more visibility thank ou for your kind understanding.

on the synopsis of Text::CSV there's this code:
my @rows; my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary att +ribute. or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!"; while ( my $row = $csv->getline( $fh ) ) { $row->[2] =~ m/pattern/ or next; # 3rd field should match push @rows, $row; } $csv->eof or $csv->error_diag(); close $fh; $csv->eol ("\r\n"); open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!"; $csv->print ($fh, $_) for @rows; close $fh or die "new.csv: $!";
I see that it pushes some rows on the array @rows, and then the array gets printed line by line inside the original file. I need to do a similar thing (like checking for a pattern and then save the row to rewrite it on another file later) but i don't need all the row, i just need a field and i need to add new fields to the $row that is been pushed.. how would i do that.

Replies are listed 'Best First'.
Re: Text::CSV module, writing some data on a csv.
by Corion (Patriarch) on Apr 06, 2016 at 10:28 UTC

    Most likely you would be doing that either by modifying $row before pushing it onto @rows or by creating your new target row by creating it from the values in $row. Where exactly do you encounter problems?

      Hi Corion thanks for your reply. How do i modify $row? how do i add items to it, remove items to it...

        $row is an array reference. See perlreftut for a gentle introduction to references. Adding and removing items to or from arrays is pretty much covered by push, pop, shift and unshift. There any many other ways (TIMTOWTDI) but those should get you started.

Re: Text::CSV module, writing some data on a csv.
by Lotus1 (Vicar) on Apr 06, 2016 at 15:43 UTC

    If you aren't familiar with array references you might try using the style below instead. It uses the parse() and fields() functions to get an array of the columns for each line.

    open(my $data, '<', $file) or die "Could not open '$file' $!\n"; while (my $line = <$data>) { chomp $line; if ($csv->parse($line)) { my @fields = $csv->fields();

    You could open an output file before the while loop, then after each line is parsed and @fields has values you can modify and print them to your new file.

    There is a nice page about CSV at Perl Maven and this Perlmonks node seems very similar to what you are trying to do. A Google search for tutorials for this module turns up lots more.

    Update: If you would like to modify existing csv files you might consider Tie::Array::CSV.