http://www.perlmonks.org?node_id=63727

This snippet does a LUHN-10 checksum calculation for testing credit card numbers. I did this a while ago when I was trying to eke a bit more oomph out of some e-commercey scripts I've got.

It benchmarks about three times faster than the implementations in both Jon Orwant's Business::CreditCard and Sean Burke's luhn_lib.pl. Anyone got any ideas to make it even faster?

Note: I hear chop() may be deprecated in Perl 6. If so, you could always use substr() instead to pick off the last digit, but chop() benchmarks faster for me than substr() in this case.

# Pre-define a mapping for the alternate digits # (rather than calculate sums in the loop every time): my @LUHN10_map = ( 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 ); # Return 1 if input number passes LUHN-10 # checksum test, otherwise return 0. sub LUHN10 { # NOTE: Assumes input consists only of digits. my $number = shift; my $sum = 0; my $length = length $number; # Sum the digits working from right to left. # Replace with mapped values for alternate # digits starting with second from right: while ( $length > 1 ) { $sum += chop $number; $sum += $LUHN10_map[ chop $number ]; $length -= 2; } $sum += $number if $length; # one digit left # if length was odd # Result for valid number must end in 0: return ( ( $sum % 10 ) == 0 ) ? 1 : 0; }