view palindrome/is_palindrome.pl @ 7:e1578d3eee36

Added is_palindrome tests.
author Eris Caffee <discordia@eldalin.com>
date Tue, 05 May 2015 12:02:16 -0500
parents
children
line source
1 use strict;
2 use warnings;
4 # This implements the same algorithm as the C++ version, but it has to first
5 # split the string into an array, and therefore uses O(N) extra space.
7 sub is_palindrome {
8 my $s = shift;
9 my @chars = split( //, $s );
10 my $first = 0;
11 my $last = scalar( @chars ) - 1;
12 while ( $first < $last ) {
13 while ( ( $chars[$first] !~ /^[a-zA-Z]$/ ) and ( $first < scalar( @chars ) ) ) {
14 $first++;
15 }
16 while ( ( $chars[$last] !~ /^[a-zA-Z]$/ ) and ( $last > 0 ) ) {
17 $last--;
18 }
20 if ( lc($chars[$first]) ne lc($chars[$last]) ) {
21 return 0;
22 }
23 $first++;
24 $last--;
25 }
26 return 1;
27 }
29 for ( my $i = 0; $i < scalar( @ARGV ) ; $i++ ) {
30 print is_palindrome( $ARGV[$i] ) . "\n";
31 }