On Fri, 2002-04-26 at 14:11, Allison Randal wrote:
> On Fri, Apr 26, 2002 at 08:49:23AM +1000, Damian Conway wrote:

> Hmmm... how about:
> 
> for $results.get_next() {
>   print $_;
>   LAST { print "Done."; }
>   ELSE { print "No results."; }
> }
> 
> The "else" of a loop construct isn't really the same as the "else" of an
> C<if>. You can't use an C<elsif> for one thing. And the condition for

Why not? What would be wrong with:

        for @x { 
                ...
        } elsif (stuff) {
                ...
        } else {
                ...
        }

Of course it brings other less wholesome things to mind like "elsfor"
and "elsloop" and "if ... elsfor" and "for ... elsif ... elsloop ...
else", but why not?

> reaching the "else" is different too, it isn't always a "false value",

Yes it is.

> sometimes it's "no values to iterate over" or "condition met before
> first execution of loop".

        while(@x) { ... }  /  if (@x) { ... }
        while($x) { ... }  /  if ($x) { ... }

These are different how? To my eye, the only difference is what happens
at the end of the block. In fact,

        while ($x) { ... ; last; }

is an if.

> I can also think of some advantages to having the "else" within the
> scope of the loop. You might want your object to return a "false" value
> from .get_next() (one that C<for> will see as non-iterate-able) but that
> still contains some interesting properties that can be used by the
> "else". If the "else" followed the loop this value wouldn't be in scope.

This is something I had not considered, but sounds very cool.

    sub alllines ($file) {
        my $fh;
        if ($fh = IO::File->new("<$file")) {
                return $fh->getlines;
        } else {
                return $! but false;
        }
    }
    
    while alllines("/etc/passwd") -> $_ {
        ...
    } else {
        die "/etc/passwd: $_";
    }

Yeah... I like it.


Reply via email to