CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Problem on Palindrome

 



iammgg
Novice

May 25, 2017, 2:59 AM

Post #1 of 3 (1187 views)
Problem on Palindrome Can't Post

It seems that there's a problem with my code. The instruction is written inside of this code (comment).

Code
#!/usr/bin/perl 
use strict;
use warnings;

=pod
Write a perl program that will check if
an input is a palindrome.
This is not case-sensitive.

Example:
Input a string: Racecar
The word Racecar is a palindrome

Input a string: hello
The word hello is not a palindrome.
=cut

print "Input a string: ";
my $string = <STDIN>;
chomp ($string);

if($string eq reverse $string) {
print "The word $string is a palindrome.\n";
}
else {
print "The word $string is not a palindrome.\n";
}


the output always says (if I input 'Racecar'), "The word Racecar is not a palindrome."

But when I input "hello" it says, "The word hello is a palindrome."

Thanks in advance.


(This post was edited by iammgg on May 25, 2017, 8:42 AM)


Laurent_R
Veteran / Moderator

May 25, 2017, 9:27 AM

Post #2 of 3 (1169 views)
Re: [iammgg] Problem on Palindrome [In reply to] Can't Post

Hi,

"Racecar" is not a palindrome because of the capital R at the beginning of the word. But if you try with "racecar" it should work properly. And "hello" is not a palindrome for me with *your* code:


Code
$ perl palindrome.pl 
Input a string: racecar
The word racecar is a palindrome.

$ perl palindrome.pl
Input a string: hello
The word hello is not a palindrome.


May be you are not running the same code as the one you posted.

If you want case-insentive palindromes, take a look at the
lc function.


iammgg
Novice

May 25, 2017, 6:52 PM

Post #3 of 3 (1161 views)
Re: [Laurent_R] Problem on Palindrome [In reply to] Can't Post

Thanks so much for the response. I tried the lc function and it works.

Here is my new code.


Code
 if(lc ($string) eq reverse lc ($string)) { 
print "The word $string is a palindrome.\n";
}

else {
print "The word $string is not a palindrome.\n";
}


and the output now is


Code
$ ./3.4_Palindrome.pl 
Input a string: Racecar
The word Racecar is a palindrome.

$ ./3.4_Palindrome.pl
Input a string: hello
The word hello is not a palindrome.


Thanks again!


(This post was edited by iammgg on May 25, 2017, 6:55 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives