in reply to Capturing occurrence counts via tr/// with variable interpolation

It's much quicker to avoid the eval by xoring with a string of 'z's and then counting the nulls:

my $ans = ( $str ^ ( $SrchStr x length $str ) ) =~ tr[\0][\0];

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
  • Comment on Re:Capturing occurrence counts via tr/// with variable interpolation
  • Download Code

Replies are listed 'Best First'.
Re^2: Capturing occurrence counts via tr/// with variable interpolation
by davidrw (Prior) on Aug 15, 2005 at 13:52 UTC
    Running that, i get:
    Can't modify bitwise xor (^) in transliteration (tr///) at /tmp/t line + 9, near "tr[\0][\0];"
    Works fine if split into two statements or modified slightly:
    my $ans = ($_=( $str ^ ( $SrchStr x length $str ) )) =~ tr[\0][\0];
    Note that it works IFF length($SrchStr)==1

      Hmm. Works for me?

      #! perl -slw use strict; use Benchmark qw[ cmpthese ]; our $str = 'azbzczdzezfzgzhzizjzkzlzmznzozpzqzrzsztzuzvzwzxzyzzz'; our $SrchStr = 'z'; my $n1 = eval "\$str =~ tr/$SrchStr/$SrchStr/"; my $n2 = ( $str ^ ($SrchStr x length $str ) ) =~ tr[\0][\0]; my $n3 = @{[ $str =~ m/$SrchStr/g ]}; print "$n1 : $n2 : $n3"; cmpthese -1, { eval => q[ my $n = eval "\$str =~ tr/$SrchStr/$SrchStr/" ], xor => q[ my $n = ( $str ^ ($SrchStr x length $str ) ) =~ tr[\0][ +\0]], match=> q[ my $n = @{[ $str =~ m/$SrchStr/g ]} ], }; __END__ [14:50:30.01] P:\test>eval-v-xor.pl 27 : 27 : 27 Rate eval match xor eval 24183/s -- -23% -98% match 31450/s 30% -- -97% xor 1127154/s 4561% 3484% --

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.