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"; }

In reply to Fall through loop by b4swine

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.