Here's yer tuit...
use Benchmark; my $string = "1234567890"; timethese(-5, { 'Regexp' => sub { $string =~ s/(.*?)(....)$/("X" +x length($1)).$2/e; }, 'Regexp D&P' => sub { $string =~ s/.(?!.{0,3}$)/x/g; +}, 'Substring' => sub { $string = length substr($string +,0,-4). substr($string,-4) } });
Yields:
Benchmark: running Regexp, Regexp D&P, Substring, each for at least 5 +CPU seconds... Regexp: 6 wallclock secs ( 5.38 usr + 0.00 sys = 5.38 CPU) @ 17 +3245.35/s (n=932060) Regexp D&P: 6 wallclock secs ( 5.30 usr + 0.00 sys = 5.30 CPU) @ 20 +0480.57/s (n=1062547) Substring: 7 wallclock secs ( 5.45 usr + 0.00 sys = 5.45 CPU) @ 10 +04355.05/s (n=5473735)
This is on a 2 GHz Pentium 4. Let's say we increase $string to 1000 characters...
Benchmark: running Regexp, Regexp D&P, Substring, each for at least 5 CPU seconds...
    Regexp:  6 wallclock secs ( 5.29 usr +  0.00 sys =  5.29 CPU) @ 4194.33/s (n=22188)
Regexp D&P:  5 wallclock secs ( 5.26 usr +  0.00 sys =  5.26 CPU) @ 2068.25/s (n=10879)
 Substring:  7 wallclock secs ( 5.26 usr +  0.00 sys =  5.26 CPU) @ 1022051.33/s (n=5375990)
Update: Added Dog_and_Pony's solution...
Update 2:Fixed stupid bug in Substring code. , and . do different things...
Update 3:abstracts spotted that my substring function has a cut and paste error (sheesh). jsprat's benchmark is accurate. The four arg substring seems to be the fastest.

/\/\averick
OmG! They killed tilly! You *bleep*!!


In reply to Re: s///e by maverick
in thread How do I replace all characters in a string with X's except the last 4 character by Anonymous Monk

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.