#! perl -slw
use strict;
use Benchmark qw[ cmpthese ];
use List::MoreUtils qw[ zip ];
sub zipA {
my( $str1, $str2 ) = @_;
$str1 =~ s/.\K/ substr $str2, 0, 1, ''/gesr;
}
sub zipB {
no warnings qw/ uninitialized /;
my( $a, $b ) = @_;
my @a1 = split( '', $a );
my @a2 = split( '', $b );
return join'', zip @a1, @a2;
}
sub zipC($$){
my( $n, $a, $b ) = ( 1, @_ );
substr( $a, $n, 0, $_), $n += 2 for split '', $b;
return $a;
};;
our $A = 'ABCDEFGHIJ';
our $B = 'abcde';
cmpthese -1, {
A => q[ my $zipped = zipA( $A, $B ); ],
B => q[ my $zipped = zipB( $A, $B ); ],
C => q[ my $zipped = zipC( $A, $B ); ],
};
__END__
C:\test>\perl5.18\perl\bin\perl.exe 1133857.pl
Rate B A C
B 43932/s -- -48% -72%
A 84167/s 92% -- -47%
C 159444/s 263% 89% --
| [reply] [Watch: Dir/Any] [d/l] |
"substr( $a, $n, 0, $_), $n += 2 for split '', $b;"
Excellent use of substr
| [reply] [Watch: Dir/Any] [d/l] [select] |
| [reply] [Watch: Dir/Any] [d/l] |
1nickt:
If it's a race, I'd expect the swift to win... ;^)
On a more serious note: Pulling in a module for such a simple task doesn't seem as good as simply making a simple subroutine and giving it a good name.
Certainly, for more intricate operations, modules can be very useful. But if you need a particular small routine (like this one), and it servers a particular purpose correctly (like this one), and it's unlikely to need maintenance (like this one), then I think a well-named subroutine beats the module seven days a week. That's the same reason I don't use File::Slurp.
For my projects, I frequently have several utility functions I use repeatedly. But rather than pull in several different modules each for a different little thing like this, I just keep my MCM::Utils module that contains all of the ones I frequently use. This way, I pull in one module, and have all of them. (Perhaps I ought to clean it up and publish a 'Robojunk' module to cpan module...)
...roboticus
When your only tool is a hammer, all problems look like your thumb.
| [reply] [Watch: Dir/Any] |
no warnings qw/ uninitialized /;
print zip @a1, @a2;
use warnings;
you can just filter the list returned by zip:
print grep { defined } zip @a1, @a2;
Hope that helps,
| [reply] [Watch: Dir/Any] [d/l] [select] |
Thanks 1nickt.
While I didn't think it would be worth the overhead of a module for something so small/simple, I do appreciate your input, and I wasn't aware of that module or function. | [reply] [Watch: Dir/Any] |
| [reply] [Watch: Dir/Any] [d/l] |