open IN, "<", "thefile.ext" or die "Cannot open file: $!\n"; my $i = 0; while (my $line = ) { $line =~ s/,39,/,3$fields[$i++],/g; # now what you want to do with $line is up to you } close IN;