This is a basic Web-based Perl Script that helps school and college students to improve their knowledge in Perl Scripting.
If you don’t know what is factorial, here is a small explanation,
Multiplying the given integer with the sequence of descending positive integers is called factorial. For example,
5! is 5 x 4 x 3 x 2 x 1 = 120
So the value of 5! is 120
We can also find the values the other way around ie.,
5! is 1 x 2 x 3 x 4 x 5 = 120
In this program, we are going to follow the above second method to find the value of the n! (n factorial)
Now, let’s see the Perl Script here:
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 |
#!/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); ##error display ends ##below line is important if you want to display the result in browser print "Content-type: text/html\n\n"; ##HTML Part print "<html> <head><title>Perl CGI Script to find Factorial of a Number</title></head> <body> <h3>Web Based Perl script to Find Factorial of a Number - <a href='http://www.tutorialsmade.com/'>Tutorialsmade.com</a></h3> <form action='' method='post'> <label>Enter Number to calculate Factorial <label> <input type='text' name='number' /> <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 param $number = $q->param('number'); $fact = 1; print "<br><br>Factorial of ", $number ," is: <br>"; ##loop till $number is less than equal to $i for($i = 1; $i <= $number; $i++) { $fact = $fact * $i; print $fact,"<br>"; } } |
Just go through the inline comments to understand the script.