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