1. Perl
  2. Date/Time

Determine if it is a leap year

The leap year determination method is as follows.

First, determine if it is divisible by 4. Being divisible by 4 is a prerequisite for a leap year. If it is not divisible by 4, it is not a leap year.

This is an example to judge whether it is a leap year.
use strict;
use warnings;

# 1900 is not a leap year, 2000 is a leap year, 2003 is not a leap year, 2004 is a leap year.
print "(1) Determine the leap year.\n";
my @years = (1900, 2000, 2003, 2004);

for my $year (@years) {
  if (is_leap_year ($year)) {
    print "$year is a leap year.\n";
  }
  else {
    print "$year year is not a leap year.\n";
  }
}

# A function that determines a leap year.
sub is_leap_year {
  my $year = shift;

  # If it is not divisible by 4, it is not a leap year.
  return if $year % 4;

  # If it is not divisible by 100 and not divisible by 400
  # Not a leap year.
  return if !($year % 100) && ($year % 400);

  # Other than that, it is a leap year.
  return 1;
}

Determine if it is a leap year.

The leap year determination method is as follows.

First, determine if it is divisible by 4. Being divisible by 4 is a prerequisite for a leap year. If it is not divisible by 4, it is not a leap year.

return if $year % 4;

Only those that are divisible by 4 in the above judgment are left. In the example example, (1900, 2000, 2003, 2004) remains (1900, 2000, 2004).

Next, make a judgment that "it is divisible by 100 and not divisible by 400". Those that meet this condition are not leap years. The 1900 meets this requirement.

return if !($year % 100) && ($year % 400);

With the above judgment, (2000, 2004) remains. These are leap years.

Related Informatrion