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; }

In reply to YAL10CI (Yet Another LUHN-10 Checksum Implementation) by larryl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.