Hello Perl language learners, school/college students here is another interesting program that will help you to understand the basic concepts of Perl CGI Web scripting such as how to get a value from the input, How to print a value etc.,
In this post, we are going to write a simple Perl program to find the entered number is a Prime number or not!
Let’s write the Perl Script:
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#!/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 number for the input box my $default_num = 96; ## change the default year to the last entered year $default_num = param("num") if request_method() eq "POST"; ##HTML Part print "<html> <head><title>Perl CGI Script to find primer number or not!</title></head> <body> <h3>Web Based Perl script to Find Primer number or not - <a href='http://www.tutorialsmade.com/'>Tutorialsmade.com</a></h3> <form action='' method='post'> <label>Enter a number <label> <input type='number' value='".$default_num."' name='num' /> <input type='submit' value='Submit' /> </form> </body> </html>"; ## here is the perl logic starts my $q = new CGI; my $c = 0; ## check if a form is submitted with $q->param() if($q->param()) { ## get the year from the input $num = lc($q->param('num')); ## loop till i equals to num for ($i = 1; $i <= $num; $i++) { ## check if the num is divisible by itself and 1 ## % modules will give the reminder value, so if the reminder is 0 then it is divisible if ($num % $i == 0) { ## increment the value of c $c++; } } ## if the value of c is 2 then it is a prime number ## because a prime number should be exactly divisible by 2 times only (itself and 1) if ($c == 2) { printf("<p style='color: green'> %d is a prime number </p>", $num); }else{ printf("<p style='color: red'> %d is not a prime number </p>", $num); } } |
Read the comments in the above program to understand it.
You can see the live demo of the above Perl Script below:
Enjoy learning. Good luck!