Let’s write a simple Perl program to find leap year, very useful for beginners and school / college students,
Formula for finding a Leap year is as follows:
1. A year should be evenly divisible by 4 (should not have a reminder):
year % 4 == 0 ( reminder should be 0 )
2. AND Year should not be evenly divisible by 100 (should have a reminder):
year % 100 != 0 ( reminder should not be 0 )
3. OR Year should be evenly divisible by 400 (should have a reminder):
year%400 == 0 ( reminder should be 0 )
So basically 1 && 2 || 3
if (1 and 2) both are true or 3 is true then it is a leap year
Here is the Perl web cgi script to find the leap year:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#!/usr/bin/perl -w ##these two lines are used to display errors on browser. If you don't want, you can remove these use CGI; use CGI::Carp qw(warningsToBrowser fatalsToBrowser); use CGI ":standard"; ##error display ends ##below line is important if you want to display the result in browser print "Content-type: text/html\n\n"; ## set the default year for the input box my $default_year = 1996; ## change the default year to the last entered year $default_year = param("year") if request_method() eq "POST"; ##HTML Part print "<html> <head><title>Perl CGI Script to find leap or not!</title></head> <body> <h3>Web Based Perl script to Find Leap year or not - <a href='http://www.tutorialsmade.com/'>Tutorialsmade.com</a></h3> <form action='' method='post'> <label>Enter the year <label> <input type='number' value='".$default_year."' name='year' /> <input type='submit' value='Submit' /> </form> </body> </html>"; ## here is the perl logic starts my $q = new CGI; ## check if a form is submitted with $q->param() if($q->param()) { ## get the year from the input $year = lc($q->param('year')); ## check if the input year is leap year or not and print accordingly if ((0 == $year % 4) && (0 != $year % 100) || (0 == $year % 400)) { print "<p><span style='color:green; font-weight:bold;'>". $year ." is a Leap Year!</span></p>"; }else{ print "<p><span style='color:red; font-weight:bold;'>". $year ." is not a Leap Year!</span></p>"; } } |
The code is self-explanatory, read the comments in the script to understand it well.
Here is the live demo of this script:
Enjoy learning. Good luck!