Here is a benchmark comparing some of the suggested methods. I run tests before and after the benchmark code to make sure I'm not mangling the source data.
use strict; use warnings; use Test::More qw{ no_plan }; use Benchmark qw{ cmpthese }; my @animals = qw{ tlephane lamec hellyfisj sctopuo nuffip slbatrosa yonkem sippopotamuh kardvara phees }; my $expected = join q{:}, qw{ elephant camel jellyfish octopus puffin albatross monkey hippopotamus aardvark sheep }; my %methods = ( bitStr => sub { my @words = @_; substr( $_, 0, 1) ^= substr( $_, -1 ) ^= substr( $_, 0, 1 ) ^= substr( $_, -1 ) for @words; return join q{:}, @words; }, reRev => sub { my @words = @_; $_ = join q{}, reverse m{(.)(.*)(.)} for @words; return join q{:}, @words; }, reSub => sub { my @words = @_; s{(.)(.*)(.)}{$3$2$1} for @words; return join q{:}, @words; }, slice => sub { my @words = @_; $_ = join q{}, ( split m{} )[ -1, 1 .. length() - 2, 0 ] for @words; return join q{:}, @words; }, ssBy2s => sub { my @words = @_; ( substr( $_, 0, 1 ), substr $_, -1 ) = ( substr( $_, -1 ), substr $_, 0, 1 ) for @words; return join q{:}, @words; }, ssNeg => sub { my @words = @_; substr( $_, 0, 1 ) = substr $_, -1, 1, substr $_, 0, 1 for @words; return join q{:}, @words; }, ); foreach my $method ( sort keys %methods ) { my $result = $methods{ $method }->( @animals ); ok( $result eq $expected, $method ); } cmpthese( -3, { map { my $codeStr = q[sub { my $ref = $methods{ ] . $_ . q[ }->( @animals ); }]; $_ => eval $codeStr; } keys %methods } ); foreach my $method ( sort keys %methods ) { my $result = $methods{ $method }->( @animals ); ok( $result eq $expected, $method ); }
Here is the output.
ok 1 - bitStr ok 2 - reRev ok 3 - reSub ok 4 - slice ok 5 - ssBy2s ok 6 - ssNeg Rate slice reSub reRev ssBy2s bitStr ssNeg slice 9667/s -- -21% -39% -56% -66% -78% reSub 12179/s 26% -- -23% -44% -57% -73% reRev 15852/s 64% 30% -- -27% -44% -64% ssBy2s 21779/s 125% 79% 37% -- -23% -51% bitStr 28212/s 192% 132% 78% 30% -- -37% ssNeg 44581/s 361% 266% 181% 105% 58% -- ok 7 - bitStr ok 8 - reRev ok 9 - reSub ok 10 - slice ok 11 - ssBy2s ok 12 - ssNeg 1..12
spliting, sliceing and joining gets the wooden spoon with the regular expression solutions being a bit faster, reverseing shading substitution. The four-substr ( list ) = ( list ) method is next fastest and the bitwise substr cascade is faster again. Fastest seems to be the assignment to a single lvalue substr of what was replaced in a four-argument substr on the RHS.
I hope this is of interest.
Cheers,
JohnGG
In reply to Re: Swap the characters
by johngg
in thread Swap the characters
by sandy1028
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |