Neil Ang

Developer

A stunning likeness of Neil Ang
Hello world

How to validate an ISBN in Perl

Posted on

The cool thing about an ISBN is that its last digit is a "check digit", which validates the rest of the number. How does it work? "It is calculated on a modulus 11 with weights 10-2, using X in lieu of 10 where ten would occur as a check digit." More info.

Here is a simple subroutine I wrote to check if a number entered is valid:

sub valid_isbn {
  my $isbn = shift;
     $isbn =~ s/[^\dX]//gi;
  return if length($isbn) != 10;
  my $sum = 0;
  my @chars = split('', $isbn);
  $chars[9] = 10 if uc($chars[9]) eq 'X';
  for (my $char = 0; $char < @chars; $char++) {
    $sum += (10-$char) * $chars[$char];
  }
  return (($sum % 11) == 0);
}

Code would not be complete without tests!

use Test::More tests => 12;

is(valid_isbn("ISBN 0843610727"), 1);
is(valid_isbn("99921-58-10-7"), 1);
is(valid_isbn("9971 5 0210 0"), 1);
is(valid_isbn("0-8044-2957-X"), 1);
is(valid_isbn("0943396042"), 1);
is(valid_isbn("0-9752298-0-X"), 1);

isnt(valid_isbn("ISBN 0843610723"), 1);
isnt(valid_isbn("91921-58-10-7"), 1);
isnt(valid_isbn("9971 5 0214 0"), 1);
isnt(valid_isbn("0-8044-2957-2"), 1);
isnt(valid_isbn("0943394042"), 1);
isnt(valid_isbn("0-9757297-0-X"), 1);