如何比较哈希值

时间:2013-04-19 08:52:42

标签: perl

我想比较哈希值,如下所示。 我需要检查......

--->如果所有哈希值都是“SUCCESS”,则只打印一次消息。

--->否则,即使单个值为“FAILURE”,也只打印另一条消息一次。

请注意,我需要在任何一种情况下打印邮件 ONLY ONCE

这是我的代码(其中一个值为“FAILURE”)

#!/usr/bin/perl -w
use strict;

my $hash = {
                1   =>  'SUCCESS',
                2   =>  'SUCCESS',
                3   =>  'SUCCESS',
                4   =>  'FAILURE',
            };

foreach my $key ( keys %$hash )
{
    if ($hash->{$key} eq 'FAILURE')
    {
        print "One of the Keys encoutered failure. Cannot proceed with Automation \n";
        last;
    }
    elsif ($hash->{$key} eq 'SUCCESS')
    {
        next;
        print "All the Keys were successful. Proceeding to Automation \n";
    }
}

输出:

One of the Keys encoutered failure. Cannot proceed with Automation

当其中一个键包含“FAILURE”时,此功能正常。

但是......当所有值都是“SUCCESS”时,这不起作用:

#!/usr/bin/perl -w
use strict;

my $hash = {
                1   =>  'SUCCESS',
                2   =>  'SUCCESS',
                3   =>  'SUCCESS',
                4   =>  'SUCCESS',
            };

foreach my $key ( keys %$hash )
{
    if ($hash->{$key} eq 'FAILURE')
    {
        print "One of the Keys encoutered failure. Cannot proceed with Automation \n";
        last;
    }
    elsif ($hash->{$key} eq 'SUCCESS')
    {
        next;
        print "All the Keys were successful. Proceeding to Automation \n";
    }
}

输出:

huh..there is no output. It brings me back to the bash shell.

现在,如果我从next循环中评论else,那么它会打印4次hte语句。

All the Keys were successful. Proceeding to Automation 
All the Keys were successful. Proceeding to Automation 
All the Keys were successful. Proceeding to Automation 
All the Keys were successful. Proceeding to Automation

问题

所以,在这种情况下,我想打印声明“所有键都成功。继续自动化”只有一次。我该怎么做?

感谢。

1 个答案:

答案 0 :(得分:3)

您对next的使用导致循环立即跳转到下一次迭代。这就是为什么你没有看到任何输出 - 程序执行永远不会到达print之后的next语句。

你可以做的是使用一个标志变量:

#!/usr/bin/perl -w
use strict;

my $hash = { 1   =>  'SUCCESS',
             2   =>  'SUCCESS',
             3   =>  'SUCCESS',
             4   =>  'SUCCESS',
           };

my $failure = 0;
foreach my $key (keys %$hash)
{
  if ($hash->{$key} eq 'FAILURE')
  {
    $failure = 1;
    last;
  }
}

if ($failure == 1) {
  print "One of the Keys encoutered failure. Cannot proceed with Automation \n";
} else {
  print "All the Keys were successful. Proceeding to Automation \n";
}
相关问题