perl - How to modify content of a file using single file handle -


i'm trying modify content of file using perl.

the following script works fine.

#!/usr/bin/perl  use strict; use warnings;  open(fh,"test.txt") || die "not able open test.txt $!"; open(fh2,">","test_new.txt")|| die "not able opne test_new.txt $!";  while(my $line = <fh>) {         $line =~ s/perl/python/i;         print fh2 $line; } close(fh); close(fh2); 

the content of test.txt:

im learning perl im in file handlers chapter 

the output in test_new.txt:

im learning python im in file handlers chapter 

if try use same file handle modifying content of file, i'm not getting expected output. following script attempts this:

#!/usr/bin/perl  use strict; use warnings;  open(fh,"+<","test.txt") || die "not able open test.txt $!";  while(my $line = <fh>) {         $line =~ s/perl/python/i;         print fh $line; } close(fh); 

incorrect output in test.txt:

im learning perl im learning python  chapter  chapter 

how modify file contents using single file handle?

as @Сухой27 answered

it's typical situation perl onliner pleasingly used.

perl -i -pe 's/perl/python/i'

perl takes below options

  • -p : make line line loop(every line assign $_ , print after evaluated $_)
  • -e : evaluate code block in above loop ( regex take $_ default operand )
  • -i : in plcae file edit (if pass arguments -i, perl preserve original files extention)

if run below script

perl -i.bak -pe 's/perl/python/i' test.txt

you modified test.txt

im learning python im in file handlers chapter 

and original text files named in test.txt.bak

im learning perl im in file handlers chapter 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -