b4swine has asked for the wisdom of the Perl Monks concerning the following question:
helloed monks,
Often I need to distinguish between a loop that ran to completion, and one that was aborted due to a last statement. For example, if I want to check if every element in a list is less than 0.5, I might write
my @list = (rand(1), rand(1), rand(1)); my $less=1; for (@list) { $less=0, last if $_>=0.5; }
At the end of this, $less will be true if all the members of the list were small, and false otherwise. I understand that this could have been done via grep in clever ways, but this is just an example. If we are doing a loop, is there a cleaner way to distinguish running a loop to completion from aborting via a last. If not, it would be a nice feature to have a system variable (or some better way), where one could write
for (@list) { last if $_ < 0.5; } my $less = $loop_ran_to_completion;
After thinking about it some more, here is an ugly looking solution, but without any temporary variables:
use Data::Dump; @list = (rand(1), rand(1), rand(1)); dd \@list; OUT: { ANY: { for (@list) { next ANY if $_ > 0.5; } # if all elements are small we come here print "All Small\n"; next OUT } # if any element is big we come here print "Some Big\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Fall through loop
by Athanasius (Archbishop) on Apr 28, 2016 at 13:55 UTC | |
|
Re: Fall through loop
by hippo (Archbishop) on Apr 28, 2016 at 14:09 UTC | |
|
Re: Fall through loop
by AnomalousMonk (Archbishop) on Apr 28, 2016 at 14:21 UTC |