Я был бы удивлен, если это не дубликат, но я не могу найти решение в любом месте для этой проблемы. Я пытаюсь заменить все экземпляры данной строки в файле другой строкой. Проблема, с которой я сталкиваюсь, заключается в том, что сценарий печатает замененную версию, но сохраняет оригинал. Я очень новой для PERL, так что я уверен, что это тривиальный вопрос, и я пропускаю что-тоPerl-файл regex не заменяет текст
Код:
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;
Оригинал Файл:
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 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.
Ожидаемый результат файла:
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.
Дополнительная информация:
$item_old
и$item_new
предоставляются пользователем. В приведенных примерах я заменялtest
наsample
.- Меня не интересует однострочное решение этой проблемы. Он должен быть интегрирован с более крупной программой, поэтому однострочные решения, которые могут запускаться с терминала, не будут слишком полезными.
Спасибо, это разрешает мою проблему. – JamoBox
Добро пожаловать. – TLP