【问题标题】:Perl If Else StatementPerl If Else 语句
【发布时间】:2012-06-07 03:42:30
【问题描述】:

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

#!/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 语句。如果读入的文本中没有“不成功”一词,则应简单地打印出“脚本成功”。但是,如果读入文件确实包含“不成功”,那么它应该记录文件中出现“错误”一词的位置并将其写入文件。帮助?!

示例输入:

吧富吧吧吧吧吧
错误:无法编译
吧吧吧吧吧吧吧
尝试失败

【问题讨论】:

  • 这将为输入文件中不包含UNSUCCESSFUL的所有行打印script successful

标签: perl if-statement


【解决方案1】:

你的语法有点不对:

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";
}

【讨论】:

  • 这只是让我脚本成功打印了大约 100 次,然后脚本在底部不成功。并且它不会写入文件
  • 是的,但是“else:”(带有冒号)的结果是什么?一个标签,什么都不做(冒号,语句删除操作符???)?什么可以检测到问题?使用“严格”模式?我们怎样才能学会钓鱼?
【解决方案2】:

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

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

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

【讨论】:

  • 好的,它负责打印每一行。但是,它不会写入文件。出于某种原因,我认为我的附加功能不起作用。它现在还说,其中包含“不成功”的脚本仍然是成功的
  • print FILE for @errors 如果你想要它到你的输出文件。我为您提供解决问题所需的信息,而不是现成的复制/粘贴解决方案。
  • 好吧,对不起。我只是真的不熟悉 Perl 的语法。对不起。
  • @user1440061 是的,我知道。输入中的一行必须包含 both UNSUCCESSFULError 才能添加到打印中,例如UNSUCCESSFUL foo: Error at bar。根据您的规格。如果这不正确,您需要提供一些示例输入。
  • 是的,抱歉,我可能不清楚。错误和不成功将在不同的行。我正在向我的原始问题添加示例输入
猜你喜欢
  • 1970-01-01
  • 2019-04-09
  • 2014-03-30
  • 2017-02-05
  • 2015-07-06
  • 2012-08-05
  • 1970-01-01
  • 2021-09-11
相关资源
最近更新 更多