Here's a short compare in benchmark terms of the two solutions. I added a third alternative using index - which can only be used for fixed strings whereas the other solutions can also use regexes. The following code was used:

use strict; use warnings; use Benchmark; our $cnt = 0; our $foo = q/abcdef/ x 10_000; Benchmark::cmpthese( 1000, { 'while' => sub {$cnt++ while $foo =~ /abc/g;}, 'subst' => sub {$cnt = $foo =~ s/abc/abc/g;}, 'index' => sub {my $POS = -1; $cnt++ while (($POS = index($foo,'abc',$POS+1)) > -1);}, }); # prints Benchmark: timing 1000 iterations of index, subst, while... index: 27 wallclock secs (25.09 usr + 0.02 sys = 25.11 CPU) @ 39 +.83/s (n=1000) subst: 15 wallclock secs (14.93 usr + 0.02 sys = 14.95 CPU) @ 66 +.89/s (n=1000) while: 18 wallclock secs (17.08 usr + 0.01 sys = 17.09 CPU) @ 58 +.53/s (n=1000) Rate index while subst index 39.8/s -- -32% -40% while 58.5/s 47% -- -12% subst 66.9/s 68% 14% --
The results vary with the length of the pattern searched for. The longer the pattern, the slower the substitution solution (as it has to substitute a longer string). The index version is always slowest. For the case where there are zero occurences of the pattern, all three alternatives take approx. the same time.

-- Hofmator


In reply to Re: tr/abc// won't use string by Hofmator
in thread tr/abc// won't use string by supernewbie

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.