I'm trying to modify content of a file using Perl.
The following script works fine.
#!/usr/bin/perl
use strict;
use warnings;
open(FH,"test.txt") || die "not able to open test.txt $!";
open(FH2,">","test_new.txt")|| die "not able to 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 I try to use same file handle for modifying the content of file, then I'm not getting expected output. The following is the script that attempts to do this:
#!/usr/bin/perl
use strict;
use warnings;
open(FH,"+<","test.txt") || die "not able to 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 do I modify the file contents using single file handle?
As @Сухой27 answered
it's typical situation that perl onliner pleasingly used.
perl
takes below options-p
: make line by line loop(every line assign into$_
and print after evaluated$_
)-e
: evaluate code block in above loop ( regex take$_
as default operand )-i
: in plcae file edit (if you pass arguments for -i, perl preserve original files with that extention)if you run below script
you will get modified
test.txt
and get original text files named in
test.txt.bak