2017-06-19 36 views
-3

我有一個文本文件,出現三次字符串'object'。每當它發生時用一個不同的字符串替換一個字符串

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

我想要寫一個Perl腳本包含在三個元件的陣列另一個字符串來替換「對象」的每次出現。數組的第一個元素與第一次出現的「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 

回答

5

有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 ; 
} 

這使總運行格局多少次匹配,並採用模運算符來選擇合適的數組元素,所以未來的命中會被替換的旋轉順序。

+3

您需要'shift @ pattern'而不是'pop'。 – Borodin

+0

好點。我會編輯它。 – Sobrique

+0

很好的答案和解釋... – ssr1012

相關問題