Linux Tips and Tricks

Linux Tips and Tricks

Palindrome in Shell Script and Perl

September10

Shell Script

Make sure you have the rev command in your system

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/sh
 
echo -n "Enter the Word : "
read word
 
reverse=$(echo $word | rev)
 
if [ "$word" = "$reverse" ]
then
	echo "The given word \"$word\" is Palindrome"
else
	echo "The given word \"$word\" is not a Palindrome"
fi

Using Perl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/perl
 
print "Enter the Word : ";
 
#Get Input from user
chomp($word = <>); 
 
#reverse the word
$reverseWord = reverse ($word);
 
#check the reversed word and user input
if ( $reverseWord eq $word )
{
   print "$word is Palindrome\n";
}
else
{
  print "$word is not Palindrome\n";
}

Perl One Liner

1
2
3
4
5
$ echo "MadaM" | perl -lane 'print $_ if(reverse($_) eq $_)';
MadaM
 
$ echo "Test" | perl -lane 'print $_ if(reverse($_) eq $_)';
$
posted under Uncategorized | No Comments »
Newer Entries »

Recent Comments

    Categories