On 3/2/07, Thomas Wittek <[EMAIL PROTECTED]> wrote:
Today I stumbled upon the Perl5 module For::Else.
It adds an else block to a foreach loop:

  foreach my $item (@items) {
    #process each item
  } else {
    #handle the empty list case
  }

I find it a very nice addition as I've written code like this:

 if (@stuff) {
   for my $thing (@stuff) {
     ..
   }
 } else {
   ..
 }

many times. An else block would save keystrokes and would make the code
more readable. Python also has it.

It will confuse the Python folks to no end (assuming they'd ever touch
anything resembling Perl).  That is not what it means in Python.  The
python else construct assumes you are looping in order to find
something:

   for x in list:
       if something(x):
           print "Found"
           break
   else:
       print "Not found"

That is, the else block is fired if you get to the end of the list
without breaking.

I'm not sure about either interpretation, but admittedly Python's is
harder to emulate clearly.   I wonder if a closure trait should do the
same thing.  Or I wonder if there's really a problem here that we're
addressing, or whether we're just adding syntax because we can.

Luke

Reply via email to