Better Living Through Thinking

Finding Palindromes

Thu, 01 Mar 2007

A few years ago, a co-worked challenged me to write a program to find palindromes. I'd forgotten about it until I just came across the code, which I present here now (named "is_palindrome"):

#!/usr/local/bin/perl -w
use strict;

## Scott Wiersdorf
## Created: Wed Apr 23 13:06:55 MDT 2003

## is_palindrome

my $str = '';
while( <> ) {
    tr/A-Z/a-z/;
    s/[^a-z]//g;
    $str .= $_;
}

if( substr($str, 0, int(length($str)/2) + length($str) % 2) eq
    scalar reverse substr($str, int(length($str)/2)) ) {
    print "Is a palindrome!\n";
    exit;
}

print "Not a palindrome.\n";
exit 1;

*is_palindrome* takes lines of stdin, strips them of any non-alphabetic characters, concatenates them together, and then looks to see if the first half of the string is the same as the last half of the string in reverse. Strings with an odd number of characters are correctly handled.

Usage: is_palindrome < palindrome.txt

You could also just 'echo' your palindrome:

$ echo 'A man, a plan, a canal: Panama!' | is_palindrome
Is a palindrome!

Here's the condensed version, if you're low on disk space:

#!perl -ln
tr/A-Z/a-z/; s/[^a-z]//g; $str .= $_;
END { $r = "not " if substr($str, 0, int(length($str)/2) +
length($str) % 2) ne scalar reverse substr($str, int(length($str)/2));
$r .= "a palindrome"; print $r }
[ category: /perl | link: finding_palindromes ]

Audio Broadcast

(standby)

Moon Status

Phase: 99.97%
Illuminated: 0.00%
Age (days): 29.52
moon phase 0.999694346338938 Sun May 20 17:34:36 MDT 2012