#!/usr/bin/perl -w use strict; use diagnostics; package main; # default namespace my @examples = ("macecad", "Racecar", "Go hang a salami; I'm a lasagna hog!", "Mississippi", "Are we not drawn onward, we few, drawn onward to new era?", "Madam, I'm Adam.", "Able was I ere I saw Elba."); print "\n"; foreach my $example(@examples) { my $output = $example . "\nThis"; if ( isPalindrome($example) ) { $output = $output . " is "; } else { $output = $output . " is not "; } $output = $output . "a palindrome.\n\n"; print $output; } exit(0); # if ( isPalindrome($example) ) sub isPalindrome { my $example = shift; $example = makeTextOnly($example); my $length = length($example); my $i = 0; my $j = $length - 1; # check equality of first & last characters # Else, complete and return "true" while ($i < $j) { # Exit at the first mismatch, returning "false" if (!(substr($example, $i, 1) eq substr($example, $j, 1))) { return 0; } ++ $i; -- $j; } return 1; } # $text = makeTextOnly($example); sub makeTextOnly { my $example = shift; # Make case-insensitive (all uppercase) $example = uc($example); # Remove whitespaces $example =~ s/\s//g; # Remove punctuation $example =~ s/[?;:!,.'"]//g; return $example; }