Hi,
the most interesting thing you may be missing all data you get from
Text::CSV using
$row = $csv->getline( $fh ) statement is an array refence and the following statement
push @rows, $row; puts this array reference to an array so you end with a data structure called array of array (AoA). You can change the data while it gets parsed as shown in the docs of the
Text::CSV or later when it's inside of AoA @rows.
Here is a sample script for change data while it's read:
# ..\perl.exe
# perlmonks http://perlmonks.org/index.pl?node_id=951536
# Text::CSV witer
use strict;
use warnings;
use Text::CSV;
my $input_file = "951536_in.csv";
my $output_file = "951536_out.csv";
my @rows;
my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary att
+ribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
#read file
open my $fh, "<:encoding(utf8)", $input_file or die "$input_file: $!"
+;
while ( my $row = $csv->getline( $fh )) {
$row->[0] =~ s/^(.*)(\d+)$/abc$2/; # replace leading chars
$row->[1] =~ s/^(.*)(\d+)$/$1asd$2/; # insert between char and di
+git
$row->[2] =~ s/^(.*)(\d+)$/$1xyz/; # replace digits
push @rows, $row;
}
$csv->eof or $csv->error_diag();
close $fh;
#write file
$csv->eol ("\n");
open my $fh_out, ">:encoding(utf8)", $output_file or die "$output_file
+: $!";
$csv->print ($fh_out, $_) for @rows;
close $fh_out or die "$output_file: $!";
print "finish!\n";
you also need this file 951536_in.csv:
a1,a2,a3
b1,b2,b3
c1,c2,c3
and the output should be like this 951536_out.csv:
abc1,aasd2,axyz
abc1,basd2,bxyz
abc1,casd2,cxyz
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.