1

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

---> 如果所有哈希值都是“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”时,这可以正常工作。

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

#!/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.

现在,如果我nextelse循环中注释掉,那么它会打印 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

问题

因此,在这种情况下,我只想打印一次“所有密钥都成功。继续自动化”的语句。 我怎样才能做到这一点?

谢谢。

4

1 回答 1

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";
}
于 2013-04-19T08:57:13.933 回答