use warnings; use strict; print checkUPC('064200115896'); sub checkUPC { # grab and immediately split upc into array, 1 char per element my @chars = split //, shift; return "should be 12 digits in length" if @chars != 12; local $| = 0; my $sum = 0; # loop through to sum even and adjusted odd chars $sum += $chars[$_] * (--$| ? 3 : 1) foreach 0..10; # calculate correct check digit my $check = (10 - $sum % 10) % 10; # return error message if wrong check digit was initially given return $check != $chars[11] ? "invalid checkdigit...should be $check" : 'Ok'; }