How to replace a token with an increase in number in Perl?
I want to replace a token in a text file with a number. The " <count>" sign , and I want it to be replaced by the number of samples so far. For example:
This <count> is a <count> count.
The <count> count increases <count><count><count>.
<count><count><count><count><count><count>
becomes:
This 1 is a 2 count.
The 3 count increases 456.
789101112
I'm not sure how to do this, maybe with some loop?
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 ++;
}
Here is a procFilescript that does what you requested:
$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.
}
Run it using cat inputFile | perl procFileand your sample file:
This <count> is a <count> count.
The <count> count increases <count><count><count>.
<count><count><count><count><count><count>
generates:
This 1 is a 2 count.
The 3 count increases 456.
789101112
.
\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;
}
Its functionally is almost identical to the hosted regex-eval solution, it just works without eval. I previously posted some anti-emergency fear, but its just FUD from other smaller languages did not do eval safely.
The / e effect effectively does this:
replace_callback( \$input, $regex, sub{
return $count++;
});
(where replacing the callback is some bloated function that does all the work)
What is really safe, like eggs, its simply not obvious that it is safe.