regex - how to replace a matched line in a file in perl? -


open fh, "+<testing.txt";  $keyfield = "ppd6";  @searchlist = qw(ppd6	16-dec-15	base5	no	yes	g_<<date>>	no	no	"n4,q2");  $fieldnumber = 3;   $valuetoset = "ravitej";  splice @searchlist, $fieldnumber,1, $valuetoset;  @lines=<fh>;  open(file,">foo.txt")|| die "can't open file write\n";  foreach $line (@lines) {      if($line =~ /$keyfield/) {          print file $searchlist;      } else {          print file $line;      }  }#end foreach  close(fh);  close(file);

**inputs: ** ppd5    31-dec-15   basel5  no  no       ppd5    23-dec-15   bas_15  no  no       ppd6    16-dec-15   bas3_15 no  no npd5    16-dec-15   bas15   no  no npd6    16-dec-15   bas15   no  no paru    9-jan-16    hjfhg15 no  no    output:   ppd5    31-dec-15   basel5  no  no       ppd5    23-dec-15   bas_15  no  no       ppd6    16-dec-15   bas3_15 ravitej no npd6    16-dec-15   bas15   no  no paru    9-jan-16    hjfhg15 no  no 

my problem after ppd6 1 row missing. can please resolve issue.

the basic rules of debugging perl program turn on strict , warnings. strict forces declare variables avoid typos, , they're not global. warnings warn of things mistakes.

after turning on warnings -w see problem immediately.

$ perl -w ~/tmp/test.plx possible attempt separate words commas @ /users/schwern/tmp/test.plx line 3. name "main::searchlist" used once: possible typo @ /users/schwern/tmp/test.plx line 11. use of uninitialized value $searchlist in print @ /users/schwern/tmp/test.plx line 11, <fh> line 6 

you print $searchlist there no such variable. if had strict on have been error you'd have seen immediately.


i have mention you're failing check "testing.txt" opened. isn't causing problem, 1 of common mistakes in perl it's worth pointing out.

open fh, "+<testing.txt"; 

it's unnecessary use +< here you're using reading. finally, i'd recommend using lexical filehandles instead of global globs automatically close when go out of scope.

later on check whether other file opens, don't include $! tell why failed open.

in general, use autodie. make (almost) every io operation throw formatted error message if fails. better having remember write "or die ..." everywhere.

use autodie;  open $fh, "<", "testing.txt"; 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -