"while/else" (ugh) (was Re: [oclug] Ruby)

Michael P. Soulier msoulier at digitaltorque.ca
Fri Jun 27 15:22:38 EDT 2003


On 27/06/03 David F. Skoll did speaketh:

> > > while not found:
> > >     line = fp.readline()
> > >     if not line: break
> > >     if re.search(pattern, line):
> > >         found = True
> > > else:
> > >     print "we didn't find the pattern"
> 
> Am I the only one who finds that repugnant?
> 
> When, exactly, does the "else" fire?  If the loop is iterated zero times?
> If the loop is ever exited with "found" still false?

    Actually, I wrote that early this morning on zero coffee, and
screwed it up. My apologies. It should be

line = 1
while line and not found:
    line = fp.readline()
    if re.search (pattern, line):
        break
else:
    print "we didn't find the pattern"

    Thus, if we exit the look without getting a pattern match and
hitting the break statement, we execute the else block. If we do break,
we skip the else. 

    It's supposed to work kinda like the 'finally' in try/catch/finally
clauses...

    Mike

-- 
Michael P. Soulier <msoulier at digitaltorque.ca>, GnuPG pub key: 5BC8BE08
"...the word HACK is used as a verb to indicate a massive amount
of nerd-like effort."  -Harley Hahn, A Student's Guide to Unix
IM: msoulier at jabber.org
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://tux.oclug.on.ca/pipermail/oclug/attachments/20030627/ed568b0e/attachment.bin


More information about the OCLUG mailing list