I would be surprised if this isn't a duplicate, but I cannot seem to find the solution anywhere for this problem. I am trying to replace all instances of a given string in a file with another string. The issue I'm having is that the script prints the replaced version but keeps the original. I'm very new to perl so I'm sure this is a trivial issue and I'm missing something
Code:
my $count;
my $fname = file_entered_by_user;
open (my $fhandle, '+<', $fname) or die "Could not open '$fname' for read: $!";
for (<$fhandle>) {
$count += s/($item_old)/$item_new/g;
print $fhandle $_;
}
print "Replaced $count occurence(s) of '$item_old' with '$item_new'\n";
close $fhandle;
Original File:
This is test my test file where
I test the string perl script with test
strings. The word test appears alot in this file
because it is a test file.
Result File:
This is test my test file where
I test the string perl script with test
strings. The word test appears alot in this file
because it is a test file
This is sample my sample file where
I sample the string perl script with sample
strings. The word sample appears alot in this file
because it is a sample file.
Expected result file:
This is sample my sample file where
I sample the string perl script with sample
strings. The word sample appears alot in this file
because it is a sample file.
Additional info:
$item_oldand$item_neware provided by the user. In the examples given I was replacingtestwithsample.- I am not interested in a one-liner solution to this problem. It is to be integrated with a larger program so one-liner solutions that can be run from the terminal won't be too helpful.