Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello everybody!

I want to ask something about loops :

I have an array, and the elements consisting it are keys to a hash.

So, I go through the array and check the value of the hash for each element of the array. On first success I want to exit the loop, but if the first element of the array does not give the wanted result in the hash, I want to continue reading the array. I use 'next' to continue reading the array if I have no success, but how do I exit the loop when the first succesful match is accomplished? Do I use 'exit' or it will terminate the whole program?

Replies are listed 'Best First'.
Re: loop question...
by sub_chick (Hermit) on May 29, 2006 at 18:09 UTC
    read up on last

    Es gibt mehr im Leben als Bücher, weißt du. Aber nicht viel mehr. - (Die Smiths)"
Re: loop question...
by xdg (Monsignor) on May 29, 2006 at 18:10 UTC

    You want to use "last". See perlsyn.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Re: loop question...
by GrandFather (Saint) on May 29, 2006 at 20:56 UTC

    Your question has been answered, this time. However it is possible that it is not the answer you want. This is because you have not given any code. It is likely that there are many areas that we can help you with even in what may seem to be a trivial piece of code. The following code is my take on what you are doing. If your actual code is very much different than this please post it so that we may highlight any other areas of concern.

    # always use strictures (the following two lines) use strict; use warnings; my @array = qw(key1 key2 key3 key4); my %hash = (key2 => undef, key4 => 'The goods', key5 => 'More goods'); for my $key (@array) { next if ! exists $hash{$key}; # Skip if the key is not used in the + hash next if ! defined $hash{$key}; # Skip if the key exists, but is un +defined print "The value for '$key' is '$hash{$key}'\n"; last; }

    Prints:

    The value for 'key4' is 'The goods'

    DWIM is Perl's answer to Gödel
A reply falls below the community's threshold of quality. You may see it by logging in.