开发者

Exactly 4 digits validation in perl

开发者 https://www.devze.com 2023-03-20 04:08 出处:网络
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 sho

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开发者_C百科 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>";
}


What about this:

if (($fiscyear1 !~ m/^\d{4}$/) or ($fiscyear2 !~ m/^\d{4}$/) or ($fiscyear1 > $fiscyear2))
   { print "Bad parameters\n"; }

I changed the ands in ors and also the final < into > (since you want the first argument is less than the second)

EDIT:

It seems that it works in my case:

Exactly 4 digits validation in perl

I also very strongly accept the advice of using ^$, and have modified my answer accordingly.


You are missing start and end of string ^ and $ in regexps (without them it can match 5 or more symbols):

use strict; use warnings;
my ($fiscyear1, $fiscyear2) = @ARGV;
if ($fiscyear1 =~ m{^\d{4}$} && $fiscyear2 =~ m{^\d{4}$} && $fiscyear1 < $fiscyear2) {
    print "good parameters\n";
} else {
    print "Bad parameters\n";
}

Update You can also use unless here like:

unless ($fiscyear1 =~ m{^\d{4}$} && $fiscyear2 =~ m{^\d{4}$} && $fiscyear1 < $fiscyear2) {
    print "Bad parameters\n";
    exit(1); ## tells the caller side that there is an error
}
print "good parameters\n";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号