Sunday, April 20, 2008

Porting Perl To Shell Again - Palindromes

Hey There,

For this "Lazy Sunday" post, we're going to take a look at a Perl script, for Linux or Unix, that checks whether or not a string you input is a palindrome. As you probably know (but I feel I should explain anyway, just to be thorough ;), a palindrome is any set of letters, numbers, spaces, etc, that reads exactly the same forward or backward.

Check out this little script and notice the use of recursion to both maintain a pseudo "state" and the use of a single subroutine to perform what could be a complex operation.

We'll port this to shell in a few days (like we've done in our post on porting a web element reporting script and its improved log checking follow up), with more explanation of what's going on, and the why and how of what gets changed when we port from Perl to shell.

Enjoy your Sunday and relax :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

#
# perlpal.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

print "Enter A String: ";
$string=<STDIN>;
chomp($string);

$chars = length($string);
@string = split(//, $string);
$count=0;
$status = palindrome( @string, $chars, $count );


if ( $status == 1 ) {
print "\n That String Is A Palindrome.\n\n";
} else {
print "\n That String Is Not A Palindrome.\n\n";
}

sub palindrome(@string, $n\chars, $count) {
if ( $string[$count] eq $string[$chars-$count-1] ) {
$count++;
palindrome($string, $chars, $count);
}
if ($count == $chars) {
return 1;
} else {
return 0;
}
}


, Mike