开发者

perl hecking all value once

I am basically a networking guy and so not good at writing scripts开发者_StackOverflow社区.

While writing some scripts I came across below requirement.

I have a hash array with some values of "1" or "2" and my requirement

if all of the value equal to other than "1" (could be "2" or "3") then it will print some statement once and then come out of that loop.

if any of the value equal to "1" then it will print some statement.

ex:

my %hash_array1=(A=>2,B=>2,C=>2);
my @array2=values (%hash_array1);

foreach my $line (@array2) {

    if ($line!=1) {

        print BOLD GREEN "\rNo Evolution ",RESET;

        last;
    }
    else {
        print BOLD RED "Evolution \n",RESET;
    }
}

which print

No Evolution

Above code work well as expected for mentioned hash_array because all values are non-"1",but not working well for below hashes

my %hash_array1=(A=>1,B=>2,C=>2);

where it prints

Evolution

No Evolution

which is not as per my expectation. I want here to print as one time "Evolution" and "No Evolution" should not be printed any more. (However loop should be continued to iterate)

Please let me know if more clarity is required.

Regards

Mahesh


my %hash_array1=(A=>2,B=>2,C=>2);
if ( grep $_ == 1, values %hash_array1 ) {
    print BOLD RED "Evolution \n",RESET;
}
else {
    print BOLD GREEN "\rNo Evolution ",RESET;
}

(Some comments are talking about execution time; this shouldn't be a concern unless it is demonstrated that there is a performance issue.)


If I'm reading your requirement correctly, you're going to need to examine the entire set unless you hit a "1"

Basically, you need to keep a state and exit the loop only if you hit a "1"

my %hash_array1=(A=>2,B=>2,C=>2);
my @array2=values (%hash_array1);
my $state = 0;

foreach my $line (@array2) 
{
    if ($line == 1)
    {
        $state = 1;
        last;
    }
}

if ($state == 1)
{
    print BOLD RED "Evolution \n",RESET;
}
else
{
    print BOLD GREEN "\rNo Evolution ",RESET;
}


I would use something like:

#!/usr/bin/perl
my %hash_array1=(A=>1,B=>1,C=>2);
my $values = join('', values(%hash_array1));

if ($values =~ /1/) {
    print "at least one 1";
} else {
    print "no 1";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜