How can I identify an argument as a year in Perl?
I have created a file argument.pl which takes several arguments first of which should be in form of a year For example: 2010 23 type
. Here 2010 is a year
my code does something like:
u开发者_Go百科se strict;
use warning
use Date::Calc qw(:all);
my ($startyear, $startmonth, $startday) = Today();
my $weekofyear = (Week_of_Year ($startyear,$startmonth,$startday))[0];
my $Year = $startyear;
...
...
if ($ARGV[0])
{
$Year = $ARGV[0];
}
Here this code fills $Year
with "current year" if $ARGV[0]
is null or doesn't exist.
What do I use here instead of if ($ARGV[0])
?
Is it possible to check that the value in $ARGV[0]
is a valid year (like 2010, 1976,1999 etc.)?
@OP, since you are using Date::Calc, looking at the documentation, you might want to try using some of the functions such as check_date()
eg
check_date
if (check_date($year,$month,$day))
if your year is not correct, the function should give you an error.
I would recommend ditching positional arguments and using a command line argument processing library such as Getopt::Long so that your program can be called as
$ argument.pl -y 2013 -d 23 -t type
You can try the following to ensure the first argument is of the format 19xx or 20xx.
if ($ARGV[0] =~/^(19|20)\d{2}$/) {
$Year = $ARGV[0];
}
Simple test for defined-ness and 4-digits format:
$Year = $ARGV[0] if defined $ARGV[0] && $ARGV[0] =~ /^\d{4}$/);
give it a try, to find the year is 20** or 19**
if ($ARGV[0] =~ m!^((?:19|20)\d\d)) {
$year = $ARGV[0];
}
Hope this helps.
精彩评论