unpack 不是拆分字符串的最快方法:
#!/usr/bin/env perl
use strict;
use List::Util qw/sum/;
use Benchmark qw/cmpthese/;
cmpthese ( -3, {
list_util => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = sum( unpack( 'AAAAAAAAA', $CheckDigit ) );
} while ( $CheckDigit > 9 );
},
unpack_star => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = sum( unpack( '(A)*', $CheckDigit ) );
} while ( $CheckDigit > 9 );
},
re => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = sum( $CheckDigit =~ /(.)/g );
} while ( $CheckDigit > 9 );
},
split => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = sum( split //, $CheckDigit );
} while ( $CheckDigit > 9 );
},
perl_only => sub {
my $CheckDigit = "999989989";
do {
$CheckDigit = unpack( '%16S*', pack( 'S9', unpack( 'AAAAAAAAA', $CheckDigit ) ) );
} while ( $CheckDigit > 9 );
},
modulo => sub {
my $CheckDigit = "999989989";
$CheckDigit = ($CheckDigit+0) && ($CheckDigit % 9 || 9);
},
} );
产生:
Rate perl_only list_util re unpack_star split modulo
perl_only 89882/s -- -15% -30% -45% -54% -97%
list_util 105601/s 17% -- -17% -35% -45% -97%
re 127656/s 42% 21% -- -21% -34% -96%
unpack_star 162308/s 81% 54% 27% -- -16% -95%
split 193405/s 115% 83% 52% 19% -- -94%
modulo 3055254/s 3299% 2793% 2293% 1782% 1480% --
因此split
,如果您必须将字符串拆分为字符,那么这似乎是您最好的选择。
但是反复对数字求和几乎与取数字 mod 9 相同(正如 mirod 指出的那样)。不同之处在于$Digits % 9
产生 0 而不是 9。一个修复它的公式是($Digits-1) % 9 + 1
,但(至少在 Perl 中)不适用于全零情况(它产生 9 而不是 0)。在 Perl 中有效的表达式是($Digits+0) && ($Digits % 9 || 9)
. 第一项处理全零情况,第二项处理正常情况,第三项将 0 更改为 9。