http://www.perlmonks.org?node_id=1019731


in reply to replace/substituion 4th field

Hi hyans.milis,

When parsing a CSV file use tested modules like Text::CSV_XS or Text::CSV, it's a lot better than re-inventing the wheel.
However, using your method, you can achieve your aim by using non-greedy regex in your if/elsif statement blocks and putting your variables $sum2 and $sum3, in the proper place like so:

... if ( $sum > 310 ) { my $sum2 = "volemd"; #chomp($sum2); not needed $line =~ s/(.*?)\,(.*?)\,(.*?)\,(.*?)\,(.*?)\,(.*?)/$1\,$2\,$3 +\,$sum2,$5,$6/g; } elsif ( $sum == 70 ) { my $sum3 = "volemd1"; #chomp($sum3); not needed $line =~ s/(.*?)\,(.*?)\,(.*?)\,(.*?)\,(.*?)\,(.*?)/$1\,$2\,$3 +\,$sum3,$5,$6/g; } ...
That should give you your expected result:
623192729079,510993192729079,19,volemd,0,133,282051608, 623192728769,510993192728769,19,310,0,118,84950715, 623192729901,510993192729901,19,volemd1,0, 623192609007,510993192609007,19,22,0, 623416771429,510993416771429,19,volemd1,0, 622319309157,510992319309157,19,22,0, 623192724581,510993192724581,19,volemd1,0, 622319381619,510992319381619,19,volemd1,0, 622198575655,510992198575655,19,1,0, 623192724589,510993192724589,19,volemd1,0, 622743581281,510992743581281,19,71,0,
Update:
Always close your open filehandles like so: close $fh or die "can't close file: $!";

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Replies are listed 'Best First'.
Re^2: replace/substituion 4th field
by scsijon (Initiate) on Feb 20, 2013 at 21:08 UTC

    I'm new to this but I'd be doing something like

    open file1 for input open file2 for output using >> so it appends .marker1. read a single line as variables $1, $2, ... use switch/case to select the field(s) you want to fix or alter change it(them) for that line of input (with case selecting fields you + want to alter in order) print to (output) file2 the variables $1,$2... check if endof input file if not goto the next line of the input file loop to .marker1. if eof input file add a print "\n"; to the output file (you usually need it) and close both input file and output file

    simple I think, but i'm a newbie