【问题标题】:How to Compare hash values如何比较哈希值
【发布时间】:2013-04-19 08:52:42
【问题描述】:

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

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

---> 否则,如果单个值是“FAILURE”,则只打印另一条消息。

请注意,无论哪种情况,我都需要打印消息仅一次

这是我的代码(其中一个值为“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.

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

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

问题

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

谢谢。

【问题讨论】:

    标签: perl


    【解决方案1】:

    您对next 的使用导致循环立即跳到下一次迭代。这就是您看不到任何输出的原因——程序执行永远不会到达next 之后的print 语句。

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

    #!/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";
    }
    

    【讨论】:

    • 您还可以在设置失败变量后通过添加last; 来缩短失败检查,因为如果一个哈希值已经出现故障,则无需检查所有哈希值。
    • @dgw:很好,添加了。
    猜你喜欢
    • 2013-10-17
    • 2022-01-04
    • 1970-01-01
    • 2016-09-08
    • 2015-01-25
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多