2016-08-02 50 views
0

我需要編輯的格式類似的文本文件:的Perl:號碼在文本文件中的每一個字的情況下

> Word text text text text 
Text 
Text 
> Word text text text text 
Text 
Text 

,使它看起來像:

>Word1 text text text text 
Text 
Text 
>Word2 text text text text 
Text 
Text 

基本上,我需要修改字符串「Word」的每個實例,並將其轉換爲「Word」,後面跟着一個與該字符串出現在文本文件中的實例數相對應的數字。我是Perl新手,不知道自己在做什麼。下面是我有:

$file = "test.txt"; 

my %count; 
my $word = " Word"; 

#Open and read data 
open (FILE, "<$file") or die "Cannot open $file: $!\n"; 
@lines= <FILE>; 
foreach my $word{ 
    my $count++; 
} 
close FILE; 

my $counter = my $count + 1; 
my $curr_ct = my $counter - my $count; 

#Open same file for editing now 
open (STDOUT, ">$file") or die "Cannot open $file: $!\n"; 


while (my $count > 0){ 
    s/ Word/Word$curr_ct/ 
    my $count--; 
    my $curr_ct = my $counter - my $count; 
    print; 
} 

close STDOUT; 
+0

'my'創建一個新變量,所以'my $ count ++;','my $ count + 1','my $ counter - my $ count'和'my $ count - '''沒有意義。 – ikegami

+0

'foreach my $ word {my $ count ++; }缺少循環的列表! – ikegami

+0

'打開文件,...'應該是'打開我的$ FILE,...'。不要使用全局變量。 – ikegami

回答

5

沒有理由使用(?{ })。當您使用/e時,替換表達式會針對每個匹配評估爲Perl代碼。這就是你需要的全部。

#!/usr/bin/perl 

use strict; 
use warnings; 

my $word = 'Word'; 

my $count; 
while (<>) { 
    s/\b\Q$word\E\b/ $word . ++$count /eg; 
    print; 
} 

5.10介紹\K這可以使關鍵線更短!

s/\b\Q$word\E\b\K/ ++$count /eg; 

其他方面的改進:

  • \b做起來很swordwordy不匹配。
  • \Q .. \E使其成爲$word可以安全地包含非單詞字符。
-1

你可以使用零寬度code evaluation expression斷言,如:(?{...})正則表達式中增加對每場比賽的計數值,然後使用該計數替代方:

請注意,根據文檔,代碼評估表達式被認爲是實驗性的。

use warnings; 
use strict; 

my $word = 'Word'; 
my $file = 'file.txt'; 

open my $fh, '<', $file or die $!; 

my $count; 

while (<$fh>){ 
    s/$word(?{$count++})/$word$count/g; 
    print; 
} 

輸入:

> Word text text text text 
Text 
Text 
> Word text text text text 
Text 
Text 

輸出:

> Word1 text text text text 
Text 
Text 
> Word2 text text text text 
Text 
Text 
+0

''我們的''應該用'local'代替'(?{})'或'(?? {})'中使用的變量,但是在'(?{})'或' {})'。 – ikegami

+1

有沒有需要花哨的實驗性的東西。這會做同樣的事情's/$ word \ K/++ $ count/eg' – Borodin

+0

@ikegami,爲什麼?他們可以被關閉或什麼? –

相關問題