Perl,运营商不工作

时间:2014-11-17 23:00:28

标签: perl

有人可以告诉我为什么我的ne运营商不在下面的if语句中工作?它正在工作,但在保存我的程序后,它已停止工作。任何帮助都会非常感激,欢呼。

$inFile = "animals.txt";
open (IN, $inFile) or
die "Can't find file: $inFile";

@animallist = (<IN>);

foreach $line (@animallist)  
{
  if ($line =~ $search)
  {
    print "$line <br> <br>";     
  }
}
if ($line ne $search)
{
  print "$search isn't in the animal list";
}

print end_html;

4 个答案:

答案 0 :(得分:5)

你似乎对你的程序做了什么感到困惑,所以我想我只是告诉你。

$inFile = "animals.txt";
open (IN, $inFile) or die "Can't find file: $inFile";
@animallist = (<IN>);

# here you define a file name, open a file, and read all of the lines
# in the file into the array @animallist

foreach $line (@animallist) {
# here you iterate over all the lines, putting each line into $line
  if ($line =~ $search) {
    print "$line <br> <br>";     
  }
# here you perform the regex match: $line =~ /$search/ and if it 
# succeeds, print $line
}
# here you end the loop

if ($line ne $search) {
  print "$search isn't in the animal list";
}
# here you take the now uninitialized variable $line and try to match 
# it against the as of yet undefined variable $search
# If both of these variables are undefined, and you are not using warnings
# it will simply return false (because "" ne "" is false)
# without warning about undefined variables in ne

您应该知道,即使您的整个行都是cat,您仍然无法使用ne将其与字符串cat进行比较,因为从文件,它有一个尾随换行符,所以它真的是cat\n。除非你chomp

似乎多余的告诉你,但当然在阅读完文件后你无法检查文件是否包含$search。你必须在阅读文件时这样做。

答案 1 :(得分:1)

尝试使用缩进,这样您就可以看到您的块何时在不适当的位置结束。

if($ line ne $ search)即使在foreach循环中,你正在填充并处理文件中的$ line。我建议把它放在块内,至少得到我认为你正在寻找的功能。

答案 2 :(得分:1)

由于我们不知道$search包含什么,因此很难知道您希望发生什么。我们假设它是您文件中动物的名称。

当您执行代码时,$search包含,例如&#34; frog&#34;并且$line包含undef(因为$line仅包含foreach循环中的数据)。这些值不相同,因此ne返回true并打印消息。

如果您要将if语句移到foreach块中,则$line会有一个值。但它仍然不会匹配,因为从仍然附加换行符的文件中读取行。和#34; Frog&#34;与#34; Frog \ n&#34;不同。您需要使用chomp()$line中删除换行符。

这与another recent question非常相似。你在做同一件作业吗?

答案 3 :(得分:0)

我认为这里有几点:

  • 对于if($ line ne $ search),$ line超出了声明它的foreach的范围,因为你没有使用strict,你不会得到错误,这个条件应始终为真。

  • 我假设$ line有换行符,所以当你用$ search匹配这个$ line时,条件可以为true,尽管字符串不相等。

假设$ line =&#34; lion \ n&#34;和$ search =&#34;狮子&#34;

然后如果你这样做($ line =〜$ search),条件将是真的,因为&#34; lion&#34;是狮子的一部分\ n&#34;串。这意味着: if($ line eq $ search)为false 如果($ line ne $ search)为真,我认为是你的情况。

你可以使用chomp($ line)函数从字符串末尾删除换行符。

我希望这会有所帮助。