20051223 6:54 by javier
Here’s an implementation of the Luhn algorithm in perl.
#!/usr/bin/perl
use strict;
my $number =
shift(@ARGV) ||
die(“Usage: $0 <number>\n“);
$number=~
s,
[^
0-
9],,g;
my($sum,
$odd);
foreach my $n (split(//,
$number)) {
$odd=!
$odd;
if($odd) {
$sum+=
$n;
} else {
my $x=
2*
$n;
$sum+=
$x>
9?
$x-
9:
$x;
}
}
my $ok =
0+
(($sum%
10)==
0);
exit(($sum%
10)!=
0);
(Download)
This program was designed for shell scripting, using something like
$ if ./luhn 457623486; then echo “ok”; else echo “error”; fi
ok
but it should be trivial to modify it for other purposes.
I’m using this algorithm to validate GSM IMEI numbers, but the Luhn algorithm is also behind credit card numbers.
This entry was posted
on Friday, December 23rd, 2005 at 6:54 and is filed under Code, General, Perl.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
December 23rd, 2005 at 11:30
You can also use this in a more tested format as Algorithm::LUHN from the CPAN.
April 26th, 2007 at 4:33
The algorithm as published is incorrect, see this patch ;)
- foreach my $n (split(//,$number)) {
+ foreach my $n (reverse split(//,$number)) {