Luhn algorithm in Perl

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.

2 thoughts on “Luhn algorithm in Perl”

  1. The algorithm as published is incorrect, see this patch ;)

    – foreach my $n (split(//,$number)) {
    + foreach my $n (reverse split(//,$number)) {

Comments are closed.