Just because there is more than one way to do it, doesn't make them all equal. I could also add the following to the list:

$char = chop $string while length $string > 4;

But, that may not be a good way to do it, although it is One More Way To Do It :)

#!/usr/bin/perl -w use Benchmark; $string = "hello world I am a string of some sort of length"; timethese(150_000, { "match" => sub { ($char) = $string =~ /^.{4}(.)/;}, "unpack" => sub { ($char) = unpack("x4 A1", $string);}, "substr" => sub { ($char) = substr($string,4,1);}, "silly" => sub { local $string; $char = chop $string while length + $string > 4;}, });

I consistently get results like so:

Benchmark: timing 150000 iterations of match, silly, substr, unpack... match: 4 wallclock secs ( 2.78 usr + 0.01 sys = 2.79 CPU) @ 53 +763.44/s (n=150000) silly: -1 wallclock secs ( 0.26 usr + -0.10 sys = 0.16 CPU) @ 93 +7500.00/s (n=150000) (warning: too few iterations for a reliable count) substr: 0 wallclock secs ( 0.48 usr + 0.00 sys = 0.48 CPU) @ 31 +2500.00/s (n=150000) unpack: 2 wallclock secs ( 1.41 usr + 0.11 sys = 1.52 CPU) @ 98 +684.21/s (n=150000)

Cheers,
KM


In reply to Re: Re: Concatenation ... Strings by KM
in thread Changing a character in the middle of a word (was: Concatenation ... Strings) by Zerhash

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.