in reply to Re: Reversed .= operator
in thread Reversed .= operator

Yes, of course, there is more than one way to do it. I would use

$string = $prefix . $string
over
substr $string, 0, 0, $prefix
myself (for readability, not because it's two fewer characters) ... but I want a (built-in) operator, dammit!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^3: Reversed .= operator
by choroba (Cardinal) on Apr 29, 2016 at 22:25 UTC
    It's not the same. substr is a bit faster, probably because it doesn't create a new string?

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Is $string =~ s/^/$prefix/; about the same speed as the substr expression?

      To me, it would more signal the intent than substr does. Then again, so does the pesky dot-between-strings notation, which 1nickt doesn't want. :-) But, as with the substr, the =~ s/^// version doesn't require duplicating $string in your statement, which is one of the benefits of the suffixing .= operator.

        Here's the benchmark code:

        Here's the result on my machine:

        ok 1 - correct concat ok 2 - same substr ok 3 - same subst 1..3 Rate subst precat substr subst 1770916/s -- -38% -47% precat 2860656/s 62% -- -15% substr 3350927/s 89% 17% --

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,