How best to write this if-else?

Carl Banks idot at vt.edu
Sat Apr 21 18:55:02 EDT 2001


Roy Smith <roy at panix.com> wrote:
> What if I want to execute different code depending on which expression I 
> matched?  Something along the lines of (pseudocode):
> 
> if (m = e1.match(line)):
>    text1 = m.group(1)
>    do_complicated_processing (text1)
> elif (m = e2.match(line)):
>    text1 = m.group(1)
>    text2 = m.group(2)
>    print text1, text2
> elif (m = e3.match(line)):
>    return


e1 = re.compile (...)
def action1 (m):
	text1 = m.group(1)
	do_complicated_processing (text1)
	return 1

e2 = re.compile (...)
def action2 (m):
	text1 = m.group(1)
	text2 = m.group(2)
	print text1, text2
	return 1

e3 = re.compile (...)
def action3 (m):
	return 0

for e,action in [(e1,action1),(e2,action2),(e3,action3)]:
	m = e.match(line)
	if m:
		if not action (m): return
		break


You might even try to construct the list automatically using something
like this:

actionlist = []
i = 1
while globals().haskey('e%d'%i):
	actionlist.append ((globals()['e%d'%i],globals()['action%d'%i]))
	i = i+1







-- 
CARL BANKS

"What is life but a series of inspired follies?"
    -- Henry Higgins in _Pygmalion_, by George Bernard Shaw



More information about the Python-list mailing list