When I first read your question I misinterpreted it. When I then later was about to post my answer I realized that your boldened sentence should be interpreted as "don't fiddle with anything but the match", whereas I first interpreted it as "don't fiddle with the newlines, at all". So my solution keeps the newlines and scatters out your 'jjjjjjj' to the same positions as "uekasdh" were found.
sub replace_keep_whitespace { my ($str, $word, $rep) = @_; $str =~ join('\\n*', split //, $word); my $match = \substr($str, $-[0], $+[0] - $-[0]); my $c = 0; $$match =~ s/[^\n]/substr($rep, $c++, 1)/eg; return $str; } my $str = <<'_DATA_'; s kkjn find ue k asd helkjadfoijejdklk _DATA_ my $word = 'uekasdh'; my $rep = 'j' x length $word; print replace_keep_whitespace($str, $word, $rep); __END__ s kkjn find jj j jjj jekjadfoijejdklk
If the replacement word is longer than the matched word then it's simply ignored at the end. If it's shorter then, well, the remaining chars are removed (but the newlines are kept).
I realize this wasn't what was asked for, but I find the solution pretty enough to post it anyway. ;-)
ihbIn reply to Re: Matching across newlines without stripping them out
by ihb
in thread Matching across newlines without stripping them out
by nysus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |