in reply to JAPH palindrome.

With all these cool responses, it is clear I needed to write myself a palindrome checker. So here goes.

#!/usr/bin/perl -w use warnings; use strict; my $text; for my $file (@ARGV) { { local $/=undef; open my $fh, '<', $file or die; $text = <$fh>; close $fh; } $text =~ s/\s//g; if ($ENV{'debug'}) { print "forwards = $text\n"; print "backwards = " . reverse($text) . "\n"; } if ($text eq reverse $text) { print "$file: Palindome OK.\n"; } else { print "$file: NOT a palindrome.\n"; } } exit 0;

This didn't seem worthy of a separate Cool Uses for Perl posting.

EDIT: Fixed based on JavaFan's comments. I no longer split the text and flip it to compare, and I do a string "is equal" compare instead of re match.

Replies are listed 'Best First'.
Re^2: JAPH palindrome.
by JavaFan (Canon) on Sep 25, 2010 at 16:57 UTC
    if ($half1 =~ $flip)
    Really? It doesn't matter if $flip contain regexp special characters, or if $flip matches $half1 partially?

    I'm also wondering why you bother splitting the text into two. Wouldn't something like:

    use Test::More; use autodie; open my $fh, "<", $file; undef $/; $text = <$fh>; chomp $text; $text =~ s/\s+//g if $lax_in_whitespace; ok $text eq reverse $text, "palindrome"; done_testing;
    be enough?

      Regarding splitting and flipping it, I guess I was too hung up on the mental steps I was taking to create a palindrome in the first place. I must have coded some analog of what my brain was doing. Twelve hours later, it looks very foolish.

      The =~ vs eq bug is just an outright screw up. I have no excuse for that one.