Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
<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:
And this does too:@foos = split(/(?=foo)/, 'foo' x 4); $foos[1] = 'bar'; undef $_; for $elem(@foos) { $_ .= $elem; } print;
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?$_ = 'foo' x 4; for(map { ++$i == 2 ? 'bar' : $_ } split(/(?=foo/, $_)) { $result .= $_; } print $result;
- A Shocked sed Addict
|
---|
Replies are listed 'Best First'. | |
---|---|
RE: Selective substitution: not in Perl?
by atl (Pilgrim) on Aug 16, 2000 at 14:25 UTC | |
by nuance (Hermit) on Aug 16, 2000 at 14:39 UTC | |
by atl (Pilgrim) on Aug 16, 2000 at 15:27 UTC | |
by merlyn (Sage) on Aug 16, 2000 at 15:33 UTC | |
by Anonymous Monk on Aug 17, 2000 at 01:46 UTC | |
by davorg (Chancellor) on Aug 16, 2000 at 14:37 UTC | |
by nuance (Hermit) on Aug 16, 2000 at 14:49 UTC | |
by davorg (Chancellor) on Aug 16, 2000 at 14:51 UTC |
Back to
Seekers of Perl Wisdom