EvanK has asked for the wisdom of the Perl Monks concerning the following question:
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:
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?# 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; }
__________
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
|
|---|