Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Write "Dumber" Functions

by danger (Priest)
on Mar 30, 2002 at 19:14 UTC ( [id://155473]=note: print w/replies, xml ) Need Help??


in reply to Write "Dumber" Functions

Your revised code can still easily die if a user enters a partial date or mistypes an underscore for a dash, consider such faulty c-l arguments as: '2002-03' or '2002-03+1'. You may want to consider just trapping the exception with an eval-block (as Juerd suggests):

#!/usr/bin/perl -w use strict; use Carp; use Date::Calc qw/check_date Localtime/; my $date = shift @ARGV || ''; my @date = split '-',$date; unless (eval{check_date(@date)}){ carp 'Invalid date supplied on command line - using current date +'; @date = (Localtime)[0..2]; } $date = join '-', @date; print "$date\n"; __END__

Rebuilding the date-string after the conditional block avoids problems that might occur later in your code if an argument like '2002-03-03-' was used (it would pass as a valid date, and there would only be three elements in @date, but the $date string would still had the trailing dash).

What I expect is for the documentation to explicitly state what will happen. Although if you just look up the docs on the check_date() routine it says it returns either true or false, earlier in the docs (under "Important Notes") it is stated that Date::Calc functions will usually die if the input values, intermediate results, or output values are of range. But then it says check_date() (and a few others) handle errors differently, returning false for invalid dates. This seems more than ambiguous about how it handles invalid parameters (number or type), and I would consider this a documentation bug. Perhaps you should contact the author with suggestions on clarifying the docs.

Personally, I generally throw an exception on invalid parameters, but in the case of a validation routine, I would usually opt to return 0 for invalidation and undef for incorrect parameters (number or type), allowing the user to just test for failure if that's all they want (as in your case).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://155473]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-19 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found