Looking over a recent adofile (designed to extract dates from free
text data entry) I wrote I looked at one section of code with a:
if strlen(trim("`exp'"))<6 { // Too short text field
local error 1
local type "unkn"
}
else { //#1 (counter for number of close braces needed)
...a lot of additional code...
// 2digit year leading separated
if regexm("`exp'","([0-9][0-9])[-,./\ ]+([0-9][0-9]?)[-,./\
]+([0-9][0-9]?)") {
local type y2/m/d
local order 20ymd
local error 7
}
else { //#8
// 0 to O substitution
if regexm("`exp'","[O]") {
local error 2
}
else { //#9
// Nothing matched
local error 3
}
}
}
}
}
}
}
}
} // close all 9 elses
I actually numbered all my open braces because I knew it was going to
be a pain to keep track of them and get them properly closed. (Using
a text editor with brace/parenthesis matching is a real boon to
avoiding mistakes.)
My real point in posting this code is that this whole exercise in
keeping track of my multiply nested elses would have been a lot
simpler if Stata had the equivalent of a -do case- command as a number
of other languages do. The -do case- construct continues until a case
has been satisfied which then passes program execution to the point
following the close of the case block. Instead of:
if #1 {
something
}
else {
if #2 {
something else
}
else {...
one could use something in the form:
docase {
case #1 {
something
}
case #2 {
something else
}
otherwise {
and something else again
}
} //end case
I'd be interested to know if anyone else has had occasion to long for
such a construct within Stata to handle the gnarly mess that occurs
when one must handle a large number of nested else- ifs. The
immediate benefit would be more readable code. I understand from
working with Foxpro that the do case construct is faster to execute
than multiple ifs, so there may be a potential for performance
improvements as well, especially if this occurs within a loop.
--
David Elliott
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/