Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Beginner's question about elegent foreachby bellaire (Hermit) |
on Feb 04, 2011 at 14:21 UTC ( [id://886212]=note: print w/replies, xml ) | Need Help?? |
For what you've got now, it's just fine. There are a couple of small changes you could make. In the first loop, many common classes that have a param method will let you do this to reduce duplication:
You could also move the third loop next to the first, since they are doing similar things, if the order isn't important. Another technique you could use, since you're curious, is a dispatch table. If you end up having a lot of kinds of these data handlers, or if they get quite large, this can be advantageous. Although it's probably overkill for only 3 different cases, here's what that would look like: If the order in which you process the fields is important, you'd have to specify it separately:
This has the advantage of putting all of your field names close together with their handler mappings. It also gives you the option of moving off very complex handlers into named subroutines instead of anonymous ones, but if you do that you'll have to pass along references to the data you're using. (This example only works because the anonymous subroutines are acting as closures, and have access to variables in the same lexical scope in which they were defined.) As stated, for only three types of field this is probably not necessary, but there more you have and the more complex your data handling becomes, the more spread out and difficult to follow your existing structure will become. Eventually all of those foreach loops start to look the same, making it harder to maintain.
In Section
Seekers of Perl Wisdom
|
|