Swedish personal and organization identity number consists of 10 digits and the tenth digit is the checksum. This Perl script calculates checksum for the identity number.
#!/usr/bin/perl
die "checksum.pl identity\n" unless @ARGV > 0 && length $ARGV[0] == 9;
sub checksum
{
my @pnr = split(//, shift);
my $n = 2;
my $sum;
foreach (@pnr) {
my $tmp = $_ * $n;
if($tmp > 9) { $sum += 1 + ($tmp % 10) }
else { $sum += $tmp; }
$n = ($n == 2) ? 1:2;
}
$tmp = substr($sum, length($sum) -1);
return ($tmp == 0) ? 0 : (10-$tmp);
}
print $ARGV[0], checksum($ARGV[0]), "\n";