2013-12-18 76 views
0
if ($time =~ /^[01]?\d\./) {  # time is 0-9 seconds or 10-19 seconds 
    $status = "OK"; 
} 
elsif ($time =~ /^(2\d|30)\./) { # time is 20-30 seconds 
    $status = "WARNING"; 
} 
else {        # any other time is critical 
    $status = "CRITICAL"; 
} 

在上面的代码中,我有一些阈值。 我需要的是改变0-10到OK,10-30到WARNING和其他所有的是CRITICAL。 该字符串是类似于1.01.11,13.512:13.52的时间。在Perl中匹配字符串

+3

是''10' OK'或'WARNING'? –

+0

可以时间消极吗? – TLP

回答

2

人们经常说,当你有一把锤子时,每一个问题开始看起来像一个钉子,在这种情况下,你正在使用模式匹配做一个简单的数字比较。

你为什么不把它们评估为数字?它会更加可维护。

$status = "CRITICAL"; 
if ($time =~ /^(\d+)\./) { # Starts with seconds 
    $seconds = $1; 
    $status = "WARNING" if ($seconds <= 30); 
    $status = "OK" if ($seconds <= 10); 
    # If status is OK, print a message 
    print "$status: Execution took $seconds seconds" if ($status eq "OK"); 
} else { 
    # Time doesn't start with seconds, so status is critical 
} 

现在,将来任何想改变阈值的人都可以修改简单数值比较器中的数字。

+0

仅供参考,请参阅发布者的较早问题:http://stackoverflow.com/questions/20620461/parsing-time-command-in-perl“$ time”变量可能包括分钟或小时,例如, '5:44.3'。 –

+0

@qwrrty如果这是真的,他的OP中的例子不起作用,因为他在字符串的起始处搜索秒。 –

+0

他们只包括分钟,如果它至少是1分钟,推测是 – ysth

2

您正在使用正则表达式来处理不适合的东西。这将是更好的

  1. 从字符串中提取数字
  2. 使用数值比较运营商分配水平

这可能是这样的:

sub level { 
    my ($time) = @_; 
    $time =~ /\A (?: (?: (?<hours>[0-9]+):)? (?<minutes>[0-9]+):)? (?<seconds>[0-9]+) [.]/x 
    or die "Can't match seconds"; 
    my $seconds = $+{seconds} + 60 * ($+{minutes} + 60*$+{hours}); 

    my $warning = 20; 
    my $critical = 31; 

    my $status = ($seconds < $warning) ? "OK" 
      : ($seconds < $critical) ? "WARNING" 
      :       "CRITICAL"; 
    return $status; 
} 

use Test::More tests => 8; 

is level("1.0"),  "OK"; 
is level("1.11"), "OK"; 
is level("13.51"), "OK"; 
is level("2:13.52"), "CRITICAL"; 
is level("26.0"), "WARNING"; 
is level("26.11"), "WARNING"; 
is level("2:26.52"), "CRITICAL"; 
is level("0:26.52"), "WARNING"; 
+0

的循环与时间命令匹配多少时间,请注意,提供的一个示例是“2:13.52”,如果有几分钟,你将死于 – ysth

+0

,应该是关键 – ysth

+0

2:13.52应该是CRITICAL '。 –