I'm still new to programming and have been working through Lerning Perl and LPORM in conjunction with the perldoc. While reading an article I came across about how credit card numbers work, I figured it was a decent opportunity to practice what I've been learning. I know this is basic code, but I was hoping that in offering it up, the monks would review it and tell me if I'm striking out syntactically/semantically and/or demonstrating ignorance of generally accepted standards/conventions.
The code runs, and does what it's supposed to. I plan on modifying it later to include validation for 13,14, and 15 digit credit card numbers as well as possibly reading a list of numbers from a text file and writing only valid numbers to a new file. I wanted to wait on expanding the program until I was sure that I wasn't completely off track.
#!/usr/perl/bin
#Simple program to check validity of 16 digit credit card numbers
use strict;
use warnings;
sub checkNumber {
my $in = shift;
my @cardNum = @{$in};
my $i = $#cardNum - 1;
while ($i >= 0) {
$cardNum[$i] = $cardNum[$i] * 2;
if ($cardNum[$i] >= 10) { $cardNum[$i] -= 9; }
$i -= 2;
}
my $total = 0;
$total += $_ foreach (@cardNum);
if ($total % 10 == 0) {
return 1;
} else {
return 0;
}
}
sub cardInfo {
my $cardNum = shift;
my $issuer;
if ($cardNum =~ /^4/) { $issuer = "VISA" }
if ($cardNum =~ /^5/) { $issuer = "MasterCard" }
if ($cardNum =~ /^6/) { $issuer = "Discover" }
print "\n Card Number: $cardNum\n";
print " Issuer: ", $issuer,"\n\n";
}
print "Enter Number: ";
chomp(my $cardNum = <STDIN>);
if ($cardNum =~ /^[0-9]+$/) {
my @number = split(//,$cardNum);
if ($#number == 15) {
if (checkNumber(\@number)) {
cardInfo($cardNum);
} else {
print "\nInvalid Card Number\n";
}
} else {
print "\n16 digit cards only for now.\n";
}
} else {
print "\nInvalid Input.\n";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.