<html>
Hi, while I was trying to convert some old sed programs which use the /n flag (substitute match n and nothing else) of the s/// operator to Perl, I was very disappointed when I discovered Perl does not support this flag. a2p/s2p do not either:
$ echo foofoofoofoo | sed 's/foo/bar/2'
foobarfoofoo
$ echo 's/foo/bar/2' | s2p
Unrecognized substitution command(2) at line 1
$ echo foofoofoofoo | awk '{print gensub(/foo/, "bar", 2)}'
foobarfoofoo
(as far as I know gensub() is only supported by GNU awk)
$ echo '{print gensub(/foo/, "bar", 2)}' | a2p
syntax error in file - at line 1
Translation aborted due to syntax errors
This code works:
@foos = split(/(?=foo)/, 'foo' x 4);
$foos[1] = 'bar';
undef $_;
for $elem(@foos)
{
$_ .= $elem;
}
print;
And this does too:
$_ = 'foo' x 4;
for(map { ++$i == 2 ? 'bar' : $_ } split(/(?=foo/, $_))
{
$result .= $_;
}
print $result;
but it's a bit too ugly for me, especially when used multiple times. Is the ability to substitute a specific match with a simple flag only found in the Land of Sed and Awk? I'm kind of suprised something as trivial as substituting an arbitrary match is simpler in sed and awk than Perl. Is there any reason selective substitution via flags was left out of Perl, or is this just an oversight? Or am I missing something obvious?
- A Shocked sed Addict