我正在尝试通过一些简单的练习来解决这个问题。我在比较两个字符串时遇到问题(一个在数组中,另一个在提供给函数)。特别是,行:
if ($el eq $iName)
即使两个字符串相等,也不会返回1。
我在这段代码上面放了一些调试行,看看那个布尔值的值是什么,好像它是undef。
#!/usr/bin/perl -w
use v5.14.0;
sub greet {
#early example - no hashes,
#if first ever name print the name,
#if not first and not previously seen, print previous names,
#if same name as one previous, acknowledge this and print previous names
my $iName = $_[0];
state @seen_names;
if (!@seen_names) {
print "Hello $iName\n";
push @seen_names, "$iName ";
} else {
my $push_name = 0;
foreach my $el (@seen_names) {
#------------------------DEBUG-----------
print "equal? ", ("$el" eq "$iName"), "----\n"; #debug - the boolean looks undef
print "equal? ", ("$el" eq undef), "----\n"; #debug
print "equal? ", ("a" eq "a"), "----\n"; #debug
#------------------------DEBUG-----------
if ($el eq $iName) { #debug - do not get into this if
#FIXME prints *all* names, including this one.
print "hello again $iName, all visitors so far: " , @seen_names, "\n";
} else {
print "hello $iName, all visitors so far: @seen_names.\n";
$push_name = 1;
}
}
if ($push_name) {
push @seen_names, "$iName ";
}
}
}
&greet ("Greg");
&greet ("Greg");
#&greet ("Bob");
#&greet ("James");
#&greet ("Jill");
我哪里错了?
答案 0 :(得分:1)
解决此问题的方法是解决以下错误,即我通过以下方式填充@seen_names:
push @seen_names, "$iName ";
还是
中的$ iNameif ($el eq $iName)
没有空格;因此if将永远失败。