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; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: YAL10CI (Yet Another LUHN-10 Checksum Implementation)
by johannz (Hermit) on Mar 12, 2001 at 10:56 UTC | |
(dkubb) Re: (2) YAL10CI (Yet Another LUHN-10 Checksum Implementation)
by dkubb (Deacon) on Mar 12, 2001 at 15:47 UTC | |
by johannz (Hermit) on Mar 12, 2001 at 22:58 UTC | |
by dkubb (Deacon) on Mar 13, 2001 at 10:09 UTC | |
by johannz (Hermit) on Mar 14, 2001 at 01:33 UTC | |
YYAL10CI
by gryng (Hermit) on Mar 12, 2001 at 22:09 UTC | |
Re: YAL10CI (Yet Another LUHN-10 Checksum Implementation)
by kschwab (Vicar) on Nov 30, 2018 at 21:14 UTC | |
Re: YAL10CI (Yet Another LUHN-10 Checksum Implementation)
by petral (Curate) on Mar 13, 2001 at 01:36 UTC |
Back to
Cool Uses for Perl