On Thu, Mar 08, 2001 at 11:37:57AM -0800, Jacob Carpenter wrote: > Let's see a subroutine that takes three (3) arguments [expr, subexpr, > replacement] -- call them whatever you like in the actual sub -- and returns > "expr" with the "subexpr" nearest the middle (currently, I intend 'middle' > to mean the byte position closest to half-the-byte-length of the string) > replaced with "replacement". Subexpr should be a literal string. and should > be centered on the middle, not begin in the middle -- i.e. > &replace_mid('aaaaa', 'aaa', 'BBB') is to return 'aBBBa' not 'aaBBB'. > > In the case that the same subexpr is found 'just-left-of-center' and > 'just-right-of-center,' you have discretion in which your sub favors -- i.e. > &replace_mid('aaaa', 'a', 'B') may return either 'aBaa' or 'aaBa'. I'd like > to see some for each way. > > I'm certain this will clearly illustrate that TMTOWTDI, and I'm looking > forward to that. Ultimately, I have a feeling that this will result in a > golf match, but initially, I'm just interested in seeing interesting ways of > doing this. I seems to recall there was a "regex in the middle" discussion, not so long ago. I think the final one-liner was substr'ing... Oh well, anyway, here is my take at the problem: sub replace_mid { my($s,$t,$r)=@_;my$l=length$s;1while$s!~ s/(.{$l,})$t(.{$l})/$1$r$2/&&--$l+1;$s; } It returns $expr unchanged if $subexpr is not present. It will also choose the right-most $subexpr, but it can be trivially changed to choose the left-most instead. Joy, Yanick -- ($_,$y)=("Yhre lo .kePnarhtretcae\n", '(.) (.)' ); $y=~s/\(/(./gwhile s/$y/$2$1/xg;print; @ !; " `---' "; ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe