This whole process involves separately summing the odd digits of the upc and multiplying it by 3, then the even digits, then summing the two results.

If I understand the whole process as you described it, this snippet does what you've described:

use strict; use warnings; use List::Util qw/sum/; my $test_number = 123456789012; $test_number =~ m/^\d{12}$/ or die "Invalid code.\n"; my( @even ) = reverse( $test_number ) =~ m/\d(\d)/g; my( @odd ) = reverse( $test_number ) =~ m/(\d)\d?/g; my $checksum = sum( @odd ) * 3 + sum( @even ); print $checksum, "\n";

I assumed (possibly errantly) that the first digit is the right-most digit (as is the case with actual numbers), and that 'odd' starts at that digit. That's why you see the use of the reverse function; to put the starting digit at the typical 'start' side of the string of digits. If you want the first digit to be the leftmost digit, simply drop the use of reverse().


Dave


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