converting from perl: variable sized unpack
Thomas Wouters
thomas at xs4all.net
Mon Jul 16 10:12:07 EDT 2001
On Mon, Jul 16, 2001 at 02:12:52PM +0200, Alex Martelli wrote:
> > I have to admit, that would be somewhat consistant with the way the rest
> > of the language works, but it sure would make it more complicated to do
> > something like:
> > if re.match (pattern1, string):
> > do stuff
> > elif re.match (pattern2, string):
> > do other stuff
> > elif re.match (pattern3, string):
> > etc, etc, etc.
> I find I can rarely throw away the match-objects in this cavalier
> way, because they carry much, often-needed information -- so, I
> don't get to use this idiom anyway. Rather, I have to code:
> mo = re1.match(thestring)
> if mo:
> dostuff(mo)
> else:
> mo = re2.match(thestring)
> if mo:
> dootherstuff(mo)
> else:
> mo = re3.match(thestring)
> if mo:
> etcetcetc(mo)
> else:
> nomatchatall()
>
> which is hardly elegant and clean.
I usually start out this way, and then end up rewriting it a bit so it fits
into something like
for reX in (re1, re2, re3, re4, re5):
m = reX.match(thestring)
if m:
do_stuff_depending_on_"m.re"_(m)
or
def do_re1(): ...
def do_re2(): ...
etc...
actions = ((re1, do_re1), (re2, do_re2))
for reX, func in actions:
if reX.match(thestring):
func(thestring)
or just build a dispatch table instead. It ends up a lot more readable and
usually a lot more *correct* than the if/elif/else version.
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list