I've written a subroutine to validate a 12-digit UPC. This involves a mathematical checksum built into the UPC-A standard...rather than going into full detail, the process is explained pretty well here.

This whole process involves seperately summing the odd digits of the upc and multiplying it by 3, then the even digits, then summing the two results. Right now, I'm accomplishing this by split()ing the upc into an array and checking a modulus of 2 on each index:

# returns error message on failure, undefined value on success sub checkUPC { # grab and immediately split upc into array, 1 char per element my @chars = split(//, shift); # return error message if incorrect length if( $#chars != 11 ) { return "should be 12 digits in length"; } # loop through to seperately sum even and odd chars foreach (0..10) { if($_ % 2 == 0) { $odd += $chars[$_]; } else { $even += $chars[$_]; } } # calculate correct check digit $mult = $check = ($odd * 3) + $even; while($mult % 10 != 0) { $mult++; } $check = $mult-$check; # return error message if wrong check digit was initially given if($check != $chars[11]) { return "invalid checkdigit...should be $check"; } # otherwise, if validated, return undefined return; }
Now, this works just fine, but I find the split() and looping seems...messy. Perhaps a fellow monk would know a more elegant and efficient way?

__________
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
- Terry Pratchett


In reply to Summing the odd/even digits of a larger number (for upc check digits)...a better way? by EvanK

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.