Golf! This checks the UPC on the command-line, and prints OK if it's good, or BAD if it's bad:
perl -le'$m=1;$s+=$_*($m^=2)for(split(//,$ARGV[0])); print(($s%10)?"BAD":"OK");'

OK, that's probably not very helpful, but contains a few useful things for a real implementation. First, you can sum the digits as you go along; you don't have to add first, then multiply. Second, odd digits get multiplied by 3 and even by 1; you can toggle between 3 and 1 by twiddling the 2 bit (since 3 ^ 2 == 1 and 1 ^ 2 == 3). Third, taking the sum, subtracting from the next highest multiple of 10, then comparing it to the check digit is the same as adding the check digit, taking the result modulo 10, and comparing to 0. Fourth, I've only been thinking about this problem for about 10 minutes, so please correct me if I'm wrong, but it does work with the test UPC. :-)

That leads to the more reasonable code:

sub check_upc { my($upc)=@_; my $m = 1; for(split(//,$upc)) { $s += $_ * ($m^=2); } return (($s%10)?"Invalid checkdigit; should be @{[10-($s-chop($upc)) +%10]}" :undef); }

In reply to Re: Summing the odd/even digits of a larger number (for upc check digits)...a better way? by sgifford
in thread 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.