Enumerate question: Inner looping like in Perl

From: Pekka Niiranen (pekka.niiranen_at_wlanmail.com)
Date: 10/30/04


Date: Sat, 30 Oct 2004 20:39:28 +0300

Hi,

I have Perl code looping thru lines in the file:

line: while (<INFILE>) {
        ...
        $_ = do something
        ...
        if (/#START/) {
                # Start inner loop
                while (<INFILE>) {
                     if (/#END/) {
                         next line;
                    }
                }
        }
        if (/#BLAH1/) {
                $_ = do something
        }
        if (/#BLAH2/) {
                $_ = do something
        }
}

I decided to use enumerate() in my Python version
since current line must be modified (the $_ = idiom in Perl)

---code starts---

fh = codecs.open(f_path, "rU", "utf-8")
contents = fh.readlines()
fh.close()

# Precompile regular expressions (speed hack?)
findSTART = r'#START'
matcherSTART = re.compile(findSTART, re.UNICODE)
findEND = r'#END'
matcherEND = re.compile(findEND, re.UNICODE)

for i, row in enumerate(contents):
        row[i] = something
        if matcherSTART.search(row):
                "Oops! how to advance 'i' and 'row' untill:
                if matcherEND.search(row):
                        continue

---code ends---

I could create extra parameter to store the state of the loop like:

foundSTART = False
for i, row in enumerate(contents):
        if foundSTART:
                if not matcherEND.search(row):
                        continue
                else:
                        foundSTART = False
        else:
                if matcherSTART.search(row):
                        foundSTART = True
                if foundBLAH1:
                        row[i] = something
                if foundBLAH2:
                        row[i] = something

but is this it really more maintainable code?

Is there enumerate() hack that I am missing or
should I go back to idiom?:

for i in range(len(contents)):
        if matcherSTART.search(row[i]):
                while not matcherEND.search(row[i]):
                        i = i + 1
                        continue

-pekka-