I'm attempting to write a Perl program to determine if a 7 character user input is a palindrome.
Without using any array, string, or reverse functions.
Desired output:
Enter in a 7 character item: 1111111
PALINDROME!
Or
Enter in a 7 character item: 1234567
NOT A PALINDROME!
This is what I have so far:
print "Enter in a 7 character item: \n";
my ($a, $b, $c, $d, $e, $f, $g);
chomp ($a=<>); chomp ($b=<>); chomp ($c=<>); chomp ($d=<>);
chomp ($e=<>); chomp ($f=<>); chomp ($g=<>);
if ($a~~$g && $b~~$g && $c~~$e){
print "PALINDROME!\n";
}
else{
print "NOT A PALINDROME! \n";
}
Unfortunately, this is giving me this result:
Enter in a 7 character item:
1
1
1
1
1
1
1
PALINDROME!
If anyone has suggestions, that would be greatly appreciated.
I look forward to hearing your input. Thank you!
That looks correct to me, after all 1111111
is a palindrome!
However, the smart match operator isn't a very useful thing, and you want to test for string equality here, so use eq
instead of ~~
.
Even better I would suggest that you allow the user to enter an entire string, so
chomp(my $str = <>);
if ( $str eq reverse($str) ) {
print "PALINDROME!\n";
}
else {
print "NOT A PALINDROME! \n";
}
Without using reverse
:
#!/usr/bin/perl
use strict;
use warnings;
my ($word) = @ARGV;
my @chars = split //, $word;
my $palindrome = 1;
for (0..@chars/2-1) {
$palindrome = $chars[$_] eq $chars[-($_+1)]
or last;
}
print "$word ".($palindrome ? "is" : "isn't")." a palindrome\n";
Usage:
script word
Changing
$b~~$g to $b~~$f might also help.
no reverse used, but regex (and recursion).
sub palyndromeP{
my $s=shift;
if (length($s)<2) {return 1}
if ($s !~ /^(.)(.*)\1$/) {return 0}
return palyndromeP($2);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.