每次发生时用一个不同的字符串替换一个字符串

时间:2017-06-19 10:35:47

标签: regex string perl text-manipulation

我有一个文本文件,其中包含三次出现的字符串'object'。

There is an object on the table
The object is under the chair
There might be an object in my pocket

我想编写一个Perl脚本,将每个'object'替换为包含在三个元素数组中的另一个字符串。数组的第一个元素与第一个出现的'object'匹配,第二个元素与第二个出现的匹配,依此类推。

例如,如果

my @pattern = ( "apple", "mango", "orange" );

然后输出必须是:

There is an apple on the table
The mango is under the chair
There might be an orange in my pocket

1 个答案:

答案 0 :(得分:4)

这是perl的一个有用功能,即/e标记为正则表达式,即表示评估表达式。

所以你可以这样做:

#!/usr/bin/env perl
use strict;
use warnings; 

my @pattern = ( "apple","mango","orange" );

while ( <DATA> ) {
   s/object/shift @pattern/eg; 
   print ;
}

__DATA__
There is an object on the table
The object is under the chair
There might be an object in my pocket

虽然请注意,因为您shift @pattern #!/usr/bin/env perl use strict; use warnings; my @pattern = ( "apple","mango","orange" ); my $hit_count = 0; while ( <> ) { s/object/$pattern[$hit_count++ % @pattern]/eg; print ; } 它会在您离开时清空。 (第4次替换将是&#39;未定义&#39;)。

但如果你想要做一个旋转模式,你可以做类似的事情。

[sources]
exten => _.,1,Answer
exten => _.,n,Playback(pbx-invalid); or put name of any sound file you want.

这样可以保持模式匹配次数的总计,并使用模运算符选择正确的数组元素,以便将来的命中数按旋转顺序替换。

相关问题