Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: perl basic count days between two dates

by talexb (Chancellor)
on Oct 03, 2013 at 21:04 UTC ( [id://1056797]=note: print w/replies, xml ) Need Help??


in reply to Re: perl basic count days between two dates
in thread perl basic count days between two dates

There's always more than one way to do it .. I like to switch things around and test for the least likely outcome first .. check to see if the year is divisible by 400, then 100, and finally 4. I think it also makes the code a little more transparent, but everyone's got their own style ..

#!/usr/bin/perl use strict; use warnings; my %testData = ( 1900 => 0, 1904 => 1, 1972 => 1, 1973 => 0, 1999 => 0, 2000 => 1, 2001 => 0, 2004 => 1 ); { foreach my $this ( keys %testData ) { if ( $testData{$this} == leapYear($this) ) { print "Correct - $this year " . ( $testData{$this} ? "is" : "is not" ) . " a leap year.\n"; } else { print "Error with $this entry ..\n"; } } } sub leapYear { my $year = shift; if ( $year % 400 ) { if ( $year % 100 ) { # 3. Simple case: it's a leap year if it's divisible by 4 return ( $year % 4 ) ? 0 : 1; } else { # 2. If it's divisible by 100: it's not a leap year. return 0; } } else { # 1. If it's divisible by 400: it's a leap year. return 1; } }

I've numbered the comments to make it a little clearer which result might be returned first, although this could be made even clearer by reversing the meaning of the conditionals so that the routine looks like this:

sub leapYear { my $year = shift; if ( $year % 400 == 0 ) { # 1. If it's divisible by 400: it's a leap year. return 1; } else { if ( $year % 100 == 0 ) { # 2. If it's divisible by 100: it's not a leap year. return 0; } else { # 3. Simple case: it's a leap year if it's divisible by 4 return ( $year % 4 ) ? 0 : 1; } } }

Alex / talexb / Toronto

Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-24 02:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found