aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJulien Fiegehenn <simbabque@cpan.org>2022-04-25 11:59:38 +0100
committerJulien Fiegehenn <simbabque@cpan.org>2022-04-25 11:59:38 +0100
commit76b126f0f4f572e051ee7d51d004c22163d83a86 (patch)
treeb8b4fa55cbc55ef18d80a68714566c3f894dad9c
parentaf5fd62b1bded1873f6d0c1d54119cfc4dddcb17 (diff)
downloadperlweeklychallenge-club-76b126f0f4f572e051ee7d51d004c22163d83a86.tar.gz
perlweeklychallenge-club-76b126f0f4f572e051ee7d51d004c22163d83a86.tar.bz2
perlweeklychallenge-club-76b126f0f4f572e051ee7d51d004c22163d83a86.zip
week 162, task 1 in Perl
-rw-r--r--challenge-162/julien-fiegehenn/perl/1.pl46
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-162/julien-fiegehenn/perl/1.pl b/challenge-162/julien-fiegehenn/perl/1.pl
new file mode 100644
index 0000000000..615f3f75c2
--- /dev/null
+++ b/challenge-162/julien-fiegehenn/perl/1.pl
@@ -0,0 +1,46 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+
+use feature 'say';
+use List::Util 'sum';
+
+# Write a script to generate the check digit of given ISBN-13 code. Please refer wikipedia for more information.
+
+# Example
+# ISBN-13 check digit for '978-0-306-40615-7' is 7.
+
+# https://en.wikipedia.org/wiki/ISBN#ISBN-13_check_digit_calculation
+
+sub isbn_13 {
+ my $number = shift;
+
+ die 'Input required' unless $number;
+
+ # clean up the number
+ $number =~ s/\D//g;
+
+ # we need to do maths on each digit
+ my @digits = split //, $number;
+
+ # discard the check digit
+ pop @digits if @digits == 13;
+
+ # do we have the right amount of digits?
+ die 'This does not look like an ISBN-13' unless @digits == 12;
+
+ # tripple all the even digits
+ $_ *= 3 for @digits[1, 3, 5, 7, 9, 11];
+
+ # and do the maths
+ return 10 - sum(@digits) % 10;
+}
+
+say isbn_13(shift);
+
+__END__
+use Test::More;
+
+is isbn_13('978-0-306-40615-7'), 7;
+
+done_testing; \ No newline at end of file