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

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

  • Comment on Re: Summing the odd/even digits of a larger number (for upc check digits)...a better way?
  • Select or Download Code