develooper Front page | perl.perl5.porters | Postings from April 2015

for / else

Thread Next
From:
Ed Avis
Date:
April 27, 2015 10:28
Subject:
for / else
Message ID:
loom.20150427T121903-680@post.gmane.org
Thanks p5-porters for taking the time to consider the various language
wishlist bugs I have posted.  If I may I'd like to draw your attention to
one more idea: for/else.

<http://psung.blogspot.co.uk/2007/12/for-else-in-python.html>
documents how it works in Python.  The 'else' clause lets you see whether the
loop was broken out of early.  So code such as

    my $bailed_out = 0;
    foreach (@items){
        if (bad($_)) {
            warn "bad item $_, bailing out";
            $bailed_out = 1;
            last;
        }
        do_item($_);
    }
    unless ($bailed_out) {
        warn 'all items processed, committing';
        commit_changes();
    }

can be simplified to

    foreach (@items) {
        if (bad($_)) {
            warn "bad item $_, bailing out";
            last;
        }
        do_item($_);
    }
    else {
        warn 'all items processed, committing';
        commit_changes();
    }

This is not always an improvement in readability, of course, but it can
often be.  And an 'else' clause after for/foreach/while is not
currently legal syntax, so this would be purely an addition to the language.

In the same way that 'last' lets you avoid extra condition variables in
loops (compared to languages like Pascal which lack it), this too lets you
do without an extra state variable to set and test.  Dare I say it, it
could even be considered more perlish.  What do you think?

P.S. a search turns up For::Else on CPAN, which is a source filter.

-- 
Ed Avis <eda@waniasset.com>



Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About