in reply to error message in the end of the array looping?

A good answer needs a little more context. For example, if the loop is in a sub then you can return rather than last when you get and have dealt with the match:

# 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'); doLoop (); sub doLoop { 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 i +s undefined next if $hash{$key} ne 'No goods'; print "The value for '$key' is '$hash{$key}'\n"; return; } print "Failed to find matching key\n" }

Prints:

Failed to find matching key

Without the sub, or if there is more work to do following the loop, you need to keep note of match success. Something like:

use strict; use warnings; my @array = qw(key1 key2 key3 key4); my %hash = (key2 => undef, key4 => 'The goods', key5 => 'More goods'); my $match = 0; 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 next if $hash{$key} ne 'No goods'; print "The value for '$key' is '$hash{$key}'\n"; $match = 1; last; } print "Failed to find matching key\n" if ! $match;

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: error message in the end of the array looping?
by dsheroh (Monsignor) on May 30, 2006 at 16:18 UTC
    In the past, I've encountered warnings from perl about exiting a loop via return and expected your first example to generate one. However, when I tested it (even after modifying key2's undef to "No goods" to get a successful match), the example code produced no such warning. So now I'm confused...

    Any idea why this example code doesn't emit a warning about exiting the loop via return? (Unfortunately, I've long since fixed my code to remove that warning and don't recall the details clearly enough to provide an example which produces it.)

      If you try to return when not in a sub you get:

      use strict; use warnings; return 10;

      Prints:

      Can't return outside a subroutine at noname2.pl line 4.

      DWIM is Perl's answer to Gödel
        That warning didn't look familiar so I poked around a little on google and it turns out that I misremembered it backwards... The actual warning I was thinking of was "Exiting subroutine via next", for which the solution is to exit from the sub using return instead of next... So return was the cure for my half-remembered warning rather than the cause.