【发布时间】:2014-03-07 03:29:36
【问题描述】:
如果这不是重复的,我会感到惊讶,但我似乎无法在任何地方找到解决此问题的方法。我正在尝试用另一个字符串替换文件中给定字符串的所有实例。我遇到的问题是脚本打印了替换的版本但保留了原始版本。我对 perl 很陌生,所以我确信这是一个微不足道的问题,我错过了一些东西
代码:
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。 - 我对这个问题的单一解决方案不感兴趣。它将与更大的程序集成,因此可以从终端运行的单行解决方案不会有太大帮助。
【问题讨论】: