Monks,

Hey all, i've written a sub that I need to tune for performance. Every bit of speed I can squeeze out of this sub will help!

I have a message string that contains a section for the substitution of random characters, indicated by {\d2} for 2 random digits. This can also be expanded to multiple sets of digits containing multiple digits for more flexibility. I send each message to a sub and it then looks for the presense of the replace string and replaces with the random digit as needed. Any help on speed would be appreciated!

Example Input: "This is a message! {\d3} --- {\d2}"

Output: "This is a message! 234 --- 31"

sub substitute { my $message = shift; my @numeric_matches = ($message =~ m/\{\\d\d+\}/g); foreach (@numeric_matches) { my $substitution = $_; my ($substitution_count) = (substitution =~ m/(\d+)/); my $number; for (1..$substitution_count) { $number .= $numeric_chars[int rand @numeric_chars]; } $substitution =~ s/\\/\\\\/g; $message =~ s/$substitution/$number/ee; } return $message; }

In reply to Speed Improvement by Nar

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.