Perl If Else声明

时间:2012-06-06 19:01:35

标签: perl if-statement

好吧,这就是我所拥有的:

#!/usr/local/bin/perl


my $argument1 = $ARGV[0];
open (LOGFILE, "<$argument1") or die "Can't find file";

open FILE, ">>output.txt" or die $!;


while(<LOGFILE>){
if (/UNSUCCESSFUL/){
    print FILE "ERROR in line $.\n" if (/Error/);
    print "script unsuccessful \n";
    else:
print "script successful \n";   }

}

close FILE;
close LOGFILE;      

我认为问题在于我的if else声明。如果在读入的文本中没有“不成功”一词,则应该只打印出“脚本成功”。但是,如果读入文件确实包含“不成功”,那么它应该记录文件中出现“错误”字样的位置并将其写入文件。救命?!

示例输入:

bar foo bar bar bar bar 错误:不会编译
酒吧酒吧酒吧吧 尝试不成功

2 个答案:

答案 0 :(得分:2)

你的语法有点不对:

if (/UNSUCCESSFUL/){
    print FILE "ERROR in line $.\n" if (/Error/);
    # Print to your file
    print FILE "script unsuccessful \n";
    #print to screen
    print "script unsuccessful \n";
} else {
    # Print to your file
    print FILE "script successful \n";
    #print to screen
    print "script successful \n";
}

答案 1 :(得分:1)

我假设您不希望为输入中不包含单词"script successful"的所有行打印"UNSUCCESSFUL"。而是将打印保存为最后一个,如果没有错误,则打印成功消息。

my @errors;
while(<LOGFILE>) {
    if (/UNSUCCESSFUL/) {
        push(@errors, "ERROR in line $.\n") if (/Error/);
    }
}

if (@errors) {
    print for @errors;
} else {
    print "script successful\n";
}