Perl:对文本文件中单词的每个实例进行编号

Adi*_* J. 0 perl text

我需要编辑一个格式如下的文本文件:

> Word text text text text
Text
Text
> Word text text text text
Text
Text
Run Code Online (Sandbox Code Playgroud)

并使它看起来像:

>Word1 text text text text
Text
Text
>Word2 text text text text
Text
Text
Run Code Online (Sandbox Code Playgroud)

基本上,我需要修改字符串"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;
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 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;
}
Run Code Online (Sandbox Code Playgroud)

引入5.10 \K可以使关键线更短!

s/\b\Q$word\E\b\K/ ++$count /eg;
Run Code Online (Sandbox Code Playgroud)

其他改进:

  • \b使它所以sword还是wordy不匹配.
  • \Q.. \E使它这样$word可以安全地包含非字字符.