in reply to Re: Randomize word
in thread Randomize word

If you're going to roll your own shuffle, there's no reason you need to work on an array:
sub rand2 { my $foo = shift; for (my $i = length($foo); --$i; ) { my $j = int rand ($i+1); (substr($foo, $i, 1), substr($foo, $j, 1)) = (substr($foo, $j, + 1), substr($foo, $i, 1)) } return $foo; }
But then, there's no strong argument for shuffling in-place, either:
sub rand3 { my $foo = shift; my $bar = ''; while (length $foo) { $bar .= substr($foo, rand(length $foo), 1, ''); } return $bar; }
Benchmark results:
Rate rand1 rand2 rand3 rand1 2928/s -- -27% -78% rand2 4008/s 37% -- -70% rand3 13282/s 354% 231% --
Update: Benchmarked BrowserUK's shuffleword; it was about half as fast as rand3.

Caution: Contents may have been coded under pressure.