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.
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With