如何在Perl中使用不断增加的数字替换令牌?

时间:2009-04-11 00:57:54

标签: perl string

我想用一个数字替换文本文件中的标记。令牌是“<count>”,我希望它被替换为目前为止的计数。例如:

This <count> is a <count> count.
The <count> count increases <count><count><count>.
<count><count><count><count><count><count>

变为:

This 1 is a 2 count.
The 3 count increases 456.
789101112

我不确定如何做到这一点,也许还有一些循环?

my $text = (the input from file, already taken care of in my script);
my $count = 1;
while( regex not found? )
{
    $text =~ s/<count>/($count);
    $count ++;
}

3 个答案:

答案 0 :(得分:15)

my $text = "whatever";
my $count = 1;
$text =~ s/<count>/$count++/ge;

应该为你做。替换结束时的/ e会产生重大影响。

答案 1 :(得分:0)

这是一个procFile脚本,可以满足您的要求:

$val = 1;                         # Initial change value.
while (<STDIN>) {                 # Process all lines.
    chomp;                        # Remove linefeed.
    $ln = $_;                     # Save it.
    $oldln = "x" . $ln;           # Force entry into loop.
    while ($oldln ne $ln) {       # Loop until no more changes.
        $oldln = $ln;             # Set lines the same.
        $ln =~ s/<count>/$val/;   # Change one occurrence if we can.
        if ($oldln ne $ln) {      # Increment count if change was made.
            $val++;
        }
    }
    print "$ln\n";                # Print changed line.
}

您使用cat inputFile | perl procFile和示例文件:

运行它
This <count> is a <count> count.
The <count> count increases <count><count><count>.
<count><count><count><count><count><count>

产生

This 1 is a 2 count.
The 3 count increases 456.
789101112

答案 2 :(得分:0)

这是另一种使用位置扫描的方法。

它使用\ G位置参考,它匹配行的开头或前一个匹配后的位置。

#!/usr/bin/perl 
use strict;      # always strict + warnings 
use warnings;

my $count = 1;   # start at 1; 

while ( my $line = <STDIN> ) {                            # read stdin 
    while ( $line =~ /\G.*?(<count>)/g ) {                 # scan left to right and pick out one <count> at a time.
        substr( $line, $-[1], $+[1] - $-[1], $count++ );  # replace the substring and increment
    }
    print $line;
}

它在功能上几乎与发布的正则表达式解决方案完全相同,只是它没有eval。我之前发布了一些反eval恐惧,但它只是来自其他较小语言的FUD没有安全地进行评估。

/ e方式实际上是这样做的:

replace_callback( \$input, $regex, sub{ 
   return $count++;
}); 

(其中,替换回调是一些可以完成所有工作的膨胀函数)

鸡蛋真的很安全,它的安全性并不明显。