Andy Armstrong writes:

> On 3 Mar 2007, at 00:39, Thomas Wittek wrote:
> > I'd like the For::Else behaviour more. Especially as I remember
> > numerous times writing an if clause to check if a list is empty
> > before  processing it.
> That's crazy. If the list is empty foreach still does the right thing  
> - there's no benefit in guarding a foreach with a conditional.

The purpose of the C<if> test is not to guard the loop but to attach an
C<else> clause to (hence the above mention of C<For::Else>), so that
some code can be run only in the case where the list is empty.

I have many times wanted this: either list the results or display a
message saying that there aren't any results; process each invoice, or
throw an error complaining there aren't any invoices.

Oooh, "or", now there's an idea.  In Perl 6 the return value of C<for>
is the list of values that successfully completed an iteration.  In the
case of their not being any items in the list to start with that will be
an empty list, which is false.  So I think this will work:

  for @invoice
  } or fail 'No invoices to process';

> > I don't remember many cases where I wrote something like this:
> > 
> >  my $found;
> >  foreach my $item (@items) {
> >    if ($item = 'foobar') {
> >      $found = 1;
> >      last;
> >    }
> >  }
> >  unless ($found) {
> >    ..
> >  }
> I'd say that or a close variation of it was a pretty common idiom.

I've many times wanted a better way of doing that too.  Basically you
want an C<else> to attach to the C<if> but only be activated if none of
the.  Larry's suggestion of using C<first> for this looks good.


Reply via email to