【问题标题】:Perl not continuingPerl 没有继续
【发布时间】:2015-11-05 08:31:29
【问题描述】:

注意:这是一个测试 perl 代码,用于检查是否有效。

我的 perl 脚本有问题,我知道可以通过添加解决方案

print "Your server is not ok, please check!\n";
die "- Server is not ok!\n";

但是在我的项目中,在die "- Server is not ok!\n"; 停止后继续脚本,我使用 print 来显示是否有效。

代码如下

#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new( timeout => 1 );
$ua->agent("007");

my $req = HTTP::Request->new( GET => 'http://www.google.com.ph/' );

my $res;
for ( 1 .. 10 ) {
    $res = $ua->request($req);
    if ( $res->is_success ) {
        print "+ Server is ok!\n";
    }
    else {
        die "- Server is not ok!\n"; # I want to stop if server is not ok and print last code. Or other solution to stop instead of using die.
    }
    sleep 1;
}
print "Your server is not ok, please check!\n"; # Why this print not showing if stop in "- Server is not ok!\n"?

看图...

停止的其他解决方案? Intead 使用die 继续执行 perl 脚本。

希望有人能解决这个小问题,谢谢大家的回复!

【问题讨论】:

  • 您到底想达到什么目的?输出似乎正确。 die 终止程序,而不是循环。有什么问题?
  • 其他方式停止HTTP::Request并打印最后一个。
  • 如果你想跳出循环,请使用last;
  • @minitech 我把它放在哪里。

标签: perl


【解决方案1】:
for ( 1 .. 10 ) {
    $res = $ua->request($req);
    if ( $res->is_success ) {
        print "+ Server is ok!\n";
    }
    else {
       print "- Server is not ok!\n"; 
       last; #this statement causes to exit the loop
    }
    sleep 1;
}

# at this point everything is oke
print "Your server is ok!\n";

【讨论】:

  • 我想在- Server is not ok!\n停下来继续或打印上一个代码。
  • 想继续 for 循环吗?
  • 所以你想循环检查所有服务器并在服务器不正常时停止......并且不检查其他服务器?
  • 感谢您的精彩回答,我的 perl 脚本现在可以完美运行。
  • 我还有一个问题,请查看pastebin.com/raw.php?i=14gfmz3N。我想你可以解决这个问题。
猜你喜欢
  • 2015-02-11
  • 2011-08-23
  • 1970-01-01
  • 2010-09-07
  • 2019-07-31
  • 2011-07-01
  • 2014-06-05
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多