tags:

views:

115

answers:

5

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:

use 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.)?

+1  A: 

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];
}
codaddict
So soon after y2k we forget all that we learned.
brian d foy
+1  A: 

Simple test for defined-ness and 4-digits format:

$Year = $ARGV[0] if defined $ARGV[0] && $ARGV[0] =~ /^\d{4}$/);
eugene y
but this passes any 4 number digit.
ghostdog74
Any four digit number is a valid year. So are any 1, 2, 3, 5, 6, 7, and 8 digit numbers. Some calendars are a bit older than the Gregorian or Julian ones. :)
brian d foy
A: 

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.

Space
That's not good for the Magna Carta. :(
brian d foy
Or just use 2 digits for the last 2 digits of the year. What could go wrong?
DVK
+3  A: 

@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.

ghostdog74
in this case user will input only year, can you please elaborate on how to use above method ? like: if (check_date($year)).........gives an error though
dexter
if you only want to check the year, one way is to give `$month` and `$day` a fix value. Pls do check the documentation to see if there are options to check only year.
ghostdog74
+3  A: 

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
Sinan Ünür