Reputation: 23502
I want to compare hash values as below. I need to check....
---> if all the hash values are "SUCCESS", then print a message only once.
---> else if even a single value is "FAILURE", then print another message only once.
Please note that I need to print the message in either case ONLY ONCE
This is my code ( with the one of the values being "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";
}
}
OUTPUT:
One of the Keys encoutered failure. Cannot proceed with Automation
This is working fine when one of the keys contain "FAILURE".
BUT..... This is not working when all the values are "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";
}
}
OUTPUT:
huh..there is no output. It brings me back to the bash shell.
Now, If I comment the next
from the else
loop, then it prints hte statement 4 times.
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
QUESTION:
So, In this case I want to print the statement "All the Keys were successful. Proceeding to Automation" only once. How can i do that?
Thanks.
Upvotes: 1
Views: 4760
Reputation: 5071
Your use of next
is causing the loop to immediately skip to the next iteration. That's why you don't see any output -- the program execution never reaches the print
statement following the next
.
What you can do is use a flag variable:
#!/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";
}
Upvotes: 3