Perl: the Markov chain saw PerlMonks

### Re^2: perl basic count days between two dates

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

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.

Create A New User
Node Status?
node history
Node Type: note [id://1056797]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-05-24 16:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (179 votes). Check out past polls.

Notices?