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. ;-)

ihb

In reply to Re: Matching across newlines without stripping them out by ihb
in thread Matching across newlines without stripping them out by nysus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.