R
Rainer Weikusat
So far, I came up with three obvious ways to do that:
$r ^= ord($1) while $string =~ /\G(.)/g;
This extracts successive characters from the string with a 'moving
regex match'.
$r ^= ord($_) for split(//, $string);
This splits the string into a list of characters and loops over that.
$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);
This loops over the 'character positions' in $string and uses substr
to extract the corresponding characters.
When benchmarking these three, the one I like best (the regex match)
comes out slowest. The 'split string, loop over list' method is about
twice as fast as the regex and the most clumsy one (IMHO), substr,
runs at about 1.5 times the speed of the split loop.
-----------------
use Benchmark;
my $string = 'A' x 100;
timethese(-3,
{
while => sub {
my $r;
$r ^= ord($1) while $string =~ /\G(.)/g;
},
for => sub {
my $r;
$r ^= ord($_) for split(//, $string);
},
substr => sub {
my $r;
$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);
}});
$r ^= ord($1) while $string =~ /\G(.)/g;
This extracts successive characters from the string with a 'moving
regex match'.
$r ^= ord($_) for split(//, $string);
This splits the string into a list of characters and loops over that.
$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);
This loops over the 'character positions' in $string and uses substr
to extract the corresponding characters.
When benchmarking these three, the one I like best (the regex match)
comes out slowest. The 'split string, loop over list' method is about
twice as fast as the regex and the most clumsy one (IMHO), substr,
runs at about 1.5 times the speed of the split loop.
-----------------
use Benchmark;
my $string = 'A' x 100;
timethese(-3,
{
while => sub {
my $r;
$r ^= ord($1) while $string =~ /\G(.)/g;
},
for => sub {
my $r;
$r ^= ord($_) for split(//, $string);
},
substr => sub {
my $r;
$r ^= ord(substr($string, $_, 1)) for 0 .. length($string);
}});