I have a validation check when I pass the command line parameters to the perl program.I pass two years first passed argument should be lesser than the second passed argument and both the arguments should be only digits and also they should be exactly 4.
#Sunny>perl check.pl 2007 2008
This is good
#Sunny>perl check.pl 2008 2007
This is bad
#Sunny>perl check.pl 200 2007
This is bad
I have written code for this but not able to figure it out why its not working.
#!usr/bin/perl
#check.pl
if ($#ARGV < 0) { }
else
{
$fiscyear1 = $ARGV[0];
$fiscyear2 = $ARGV[1];
}
if (($fiscyear1 !~ m/\d{4}/) and ($fiscyear2 !~ m/\d{4}/) and ($fiscyear1 < $fiscyear2))
{ print "Bad parameters\n"; }
else
{ print "good parameters\n"; }
This sounds like a bad case of overthinking things...
What you want is to verify that the arguments are two years, in the form YYYY, and that the second year comes after the first.
Well, 9999 would pass any digit check, but it is hardly a valid year. Same with 0101, or 3021, etc.
What you want is to set a given range, and make sure the arguments are numeric.
use strict;
use warnings;
my $yr1 = shift;
my $yr2 = shift || usage();
usage() unless $yr1 =~ /^\d+$/;
usage() unless $yr2 =~ /^\d+$/;
my $min_year = 1900;
my $max_year = 2200;
if ( ($yr1 < $min_year) or ($yr1 > $max_year) ) {
die "Invalid year: $yr1";
}
if ( ($yr2 < $min_year) or ($yr2 > $max_year) ) {
die "Invalid year: $yr2";
}
if ( $yr1 >= $yr2 ) {
die "Invalid sequence: $yr2 is not greater than $yr1";
}
sub usage {
die "Usage script.pl <year1> <year2>";
}