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.