While it probably doesn't matter much in many real world situations, I think it's worth mentioning that the tr/// method of transliterating single characters is much more efficient than the s///g method. s///g is, of course, a good way to do it if you're trying to work on multiple characters or complex situations. But for simple "dumb" single-character replacement, tr/// is the right tool for the job.

The following takes a string of 10,000 characters, and changes all of the characters to an alternate character, and then changes them back to their original state... and repeats that approach 5,000 times for each operator (tr/// and s///g). The results are dramatic, but in real world applications how many times are you going to be performing 5000 iterations of replacing 10,000 single characters? ;)

use strict; use warnings; use Benchmark; my $string = '.' x 10000; sub tr_test { $string =~ tr/./_/; $string =~ tr/_/./; } sub s_test { $string =~ s/\./_/g; $string =~ s/_/./g; } my $count = 5000; timethese ( $count, { 'TR' => \&tr_test, 'S' => \&s_test } ); __OUTPUT__ Benchmark: timing 5000 iterations of S, TR... S: 48 wallclock secs (46.95 usr + 0.01 sys = 46.96 CPU) @ 106.48/s (n=5000) TR: 0 wallclock secs ( 0.58 usr + 0.00 sys = 0.58 CPU) @ 8605.85/s (n=5000)

The speed difference is both understandable and breathtaking. And in some applications it might even matter, while in others, it might not. ;)


Dave


In reply to Re: Replace all . with _ in a string by davido
in thread Replace all . with _ in a string by cshields36

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.