Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to catch "for loop reached last element"?

Sometimes in Perl, I write a for / foreach loop that iterates over values to check a value against a list. After the first hit, the loop can exit, as we've satisfied my test condition. For example, this simple code:

my @animals = qw/cat dog horse/;

foreach my $animal (@animals)
{
  if ($input eq $animal)
  {
    print "Ah, yes, an $input is an animal!\n";
    last;
  }
}
# <-----

Is there an elegant way - an overloaded keyword, maybe - to handle "for loop reached last element"? Something to put at the arrow above?

I can think of ways to do this, like creating / setting an additional $found variable and testing it at the end.... But I was hoping Perl might have something else built in, like:

foreach my $animal (@animals)
{
  if ($input eq $animal)
  {
    print "Ah, yes, an $input is an animal!\n";
    last;
  }
} finally {
  print "Sorry, I'm not sure if $input is an animal or not\n";
}

which would make this test more intuitive.

like image 555
Greg Kennedy Avatar asked Jan 27 '23 23:01

Greg Kennedy


1 Answers

You can wrap your loop with a labeled block like so:

outer: {
    foreach my $animal (@animals) {
        if ($input eq $animal) {
            print "Ah, yes, an $input is an animal!\n";
            last outer;
        }
    }
    print "no animal found\n";
}
like image 123
clamp Avatar answered Jan 29 '23 14:01

clamp