[英]In Perl, how can I test if a string is a palindrome?
I'm attempting to write a Perl program to determine if a 7 character user input is a palindrome.我正在尝试编写一个 Perl 程序来确定 7 个字符的用户输入是否为回文。
Without using any array, string, or reverse functions.不使用任何数组、字符串或反向函数。
Desired output:所需的 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!这对我来说是正确的,毕竟1111111
是一个回文!
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 ~~
.但是,智能匹配运算符并不是一个非常有用的东西,并且您想在这里测试字符串相等性,因此请使用eq
而不是~~
。
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
:不使用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. $b~~$g 到 $b~~$f 也可能有帮助。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.