Here's how I'd do it...
use Modern::Perl; say "Enter a word... maybe it's a palindrome...?"; chop(my $input = lc <>); my $reversed = join q(), reverse split q(), $input; say $reversed eq $input ? "yeah" : "nah";
... but don't submit that as-is. Learn from it and write your own.
The chop() function I only use once here, to remove the line-break character from the user input. chop not only tells you what the last character was in the string, it also modifies the string! Thus your comparison at the end will never work, because by the time you've chopped $user nine times, it'll be empty.
(Plus comparing an array and a string using "==" doesn't do what you seem to think it will do.)
Here's a version somewhat closer in spirit to your version:
use Modern::Perl; # Get a line from the user, and remove the # trailing line break say "Enter a word..."; chop(my $user = lc <>); # Keep a copy of the user input because we're # about to totally destroy $user. my $original = $user; # An array that we're going to split the # input into. my @userinput; # Keep going while there's still some input. while (length $user) { # Chop takes a character from the end # of the string. Unshift adds something # to the start of the array. So this # reverses the string as it goes! unshift @userinput, chop $user; } # Now join the array back into a string. my $reversed = join q(), @userinput; if ($original eq $reversed) { say "PALINDROME"; } else { say "NOT A PALINDROME"; }
In reply to Re: Please help
by tobyink
in thread Please help
by Camerontainium
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |