On Sat, Mar 03, 2007 at 01:39:35AM +0100, Thomas Wittek wrote:
: Luke Palmer schrieb:
: > That is not what it means in Python.
: 
: You trapped me. :) Actually I don't know any python but I've once read a
: for/else construct in python. But obviously it doesn't dwIm.
: 
: >From the Python Reference Manual:
: 
:   When the items are exhausted (which is immediately when the sequence
:   is empty), the suite in the else clause, if present, is executed,
:   and the loop terminates.
: 
: > I'm not sure about either interpretation, but admittedly Python's is
: > harder to emulate clearly.

Well, that's assuming you come at it only with the 'for' loop.  But this
is still Perl, so there's still more than one way to do it.  :-)

    $result = first { .something }, @items
        err fail "nothing found";

: 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.
: 
: 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) {
:     ..
:   }

If you actually wrote that, then you'll always find that the first
item has the value 'foobar'.  :)

: To make it more clear, I could imagine (a subset of) this:
: 
:   for @items -> $item {
:     say $item;
:     if $item == 42 {
:       say "I've found the Answer to Life, the Universe, and Everything!";
:       last;
:     }
:   } start {
:     say "Mh, I'll look for 42!"
:   } end {
:     say "The end has been reached. 42 not found."
:   } empty {
:     say "No items."
:   }

Well, leaving out the extraneous stuff, here's both kinds of "else" in one:

    $result = first 42, (@items || say "No items.")
        err say "The end has been reached. 42 not found.";

To get all of it in, you could use something more like:

    $result = first Any, gather for @items || say "No items." {
        FIRST { 
            say "Mh, I'll look for 42!"
        }
        when 42 {
            say "I've found the Answer to Life, the Universe, and Everything!";
            take $_;
        }
        LAST {
            say "The end has been reached. 42 not found.";
        }
    }

That's assuming the LAST never runs because the gather never requests
a second take.  (And also assuming that when the loop is GC'd it also
doesn't run LAST.)  Note that in either case we're using smartmatch,
so you're not going to make the =/== mistake.

Perhaps there should be something like the "first gather" that does
the gather assuming only one thing will be gathered.  Unfortunately
"item gather" will still gather everything and make it [list].

Larry

Reply via email to