Mahesh
Mahesh

Reputation: 233

perl hecking all value once

I am basically a networking guy and so not good at writing scripts.

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

Upvotes: 0

Views: 92

Answers (3)

user180100
user180100

Reputation:

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";
}

Upvotes: 0

ysth
ysth

Reputation: 98388

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.)

Upvotes: 4

Brian Roach
Brian Roach

Reputation: 76898

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;
}

Upvotes: 2

Related Questions