In this tutorial we are going to see how to write a Perl program to check the entered string is Palindrome or not.
What you will learn from this program?
1. Removing space between words in Perl.
2. Removing special characters from a string in Perl.
3. Changing string to lowercase in Perl.
4. How to reverse a string in Perl.
5. Comparing two strings in Perl.
Basically, Palindrome is a word or sequence that reads backward as forwards.
These are the example phrases,
1. Madam
2. No lemon, no melon.
3. Civic
4. Nurses run
5. Madam, I’m Adam
So all we have to do is reverse the string and compare it with the original string, if both are equal then it is a Palindrome.
Here is the Perl web script to find a string is a Palindrome or not:
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 |
#!/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 vowels in a string</title></head> <body> <h3>Web Based Perl script to Find Vowels in a string - <a href='http://www.tutorialsmade.com/perl-web-script-to-find-a-string-is-palindrome-or-not/'>Tutorialsmade.com</a></h3> <form action='' method='post'> <label>Enter a string or phrase <label> <input type='text' name='string' /> <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()) { ## change to lower case $string = lc($q->param('string')); ## remove space between words $string=~s/ //g; ## remove special characters $string =~ s/[^A-Za-z0-9]//g; ## reverse the string and store it in a new varaible called $reverse $reverse = reverse($string); ## check if the original string and reversed is equal or not ## if equal then it is palindrom if($string eq $reverse){ print "<p>It is Palindrome</p>"; }else{ print "<p>It is not Palindrome</p>"; } } |
The code is self-explanatory, just read the comments in the program to understand it step by step.
Enjoy coding!