从文件

时间:2018-03-21 18:27:15

标签: perl if-statement

我有以下代码,其输入文件“fruits.txt”具有以下值。

Apple
Mango
Grapes
Bananas
Avocado

我得到的输出如下;

Grapes not in list
Strawberry not in list
Grapes not in list
Strawberry not in list
Grapes
Strawberry not in list
Grapes not in list
Strawberry not in list
Grapes not in list
Strawberry not in list
Grapes not in list
Strawberry not in list

但是,我实际上正在寻找这样的输出,请帮忙!

预期结果如下。

Grapes
Strawberry not in list

代码:

use strict;
use warnings;

open (FILE,"fruits.txt");
    while (<FILE>) {
     if (/Grapes/) {
       print $_;
     } else { print "Grapes not in list\n";}
     if (/strawberry/i) {
       print $_;
     }
     else {
       print "Strawberry not in list\n";
     }
}
close FILE;

提前致谢。

1 个答案:

答案 0 :(得分:3)

没有#34;不在列表中#34;如果您需要浏览整个列表以知道列表中的项目不在内,则在循环内打印。所以让我们把它们移出去。

use strict;
use warnings qw( all );

open(my $FILE, "<", "fruits.txt")
   or die("Can't open \"fruits.txt\": $!\n");

my $saw_grapes     = 0;
my $saw_strawberry = 0;

while (<$FILE>) {
    ...
}

print "Grapes not in list\n"     if !$saw_grapes;
print "Strawberry not in list\n" if !$saw_strawberry;

其余的应该是显而易见的。

$saw_grapes     ||= /grapes/i;
$saw_strawberry ||= /strawberry/i;