Your skill will accomplish what the force of many cannot |
|
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Nice solution, but I feel it would be beautiful if one's function has only one return, instead of two or more.Why? I do not think it is wrong to have multiple exit points for a subroutine. Especially not in such a context. In the old times when Wirth, Dijkstra, and others were (rightly) trying to promote structured programming (against the spaghetti plates of goto's that were prevalent at the time), some over-zealous structured programming bigots insisted that all functions (and loops) should have only one entry point and one exit point. For the entry point, fair enough, that's what most modern programming languages offer anyway. But having multiple return statement is fairly legitimate: you look for a value (e.g. in an array, a file, etc?) and return it immediately when you find it, and return something else (undef, false value, failure message, etc.) if you traversed the whole array or read the whole file and did not find what you were looking for. There is nothing wrong with that. Just like having multiple next and last control statements in a loop is perfectly OK and often allows for more natural code than multiple flags. Using a flag and a last statement, as you're suggesting, is also an entirely legitimate way of doing it, but I do not think it is any better (or worse, for that matter) than thanos1983's solution. TIMTOWTDI. If I dare quoting my own book on Perl 6: ... the one-exit notion has led people to bend over backwards and write a lot of unnatural code. Much of programming consists of traversing decision trees. A decision tree naturally starts with a single trunk but ends with many leaves. Write your code with the number of loop controls (and subroutine exits) that is natural to the problem you’re trying to solve. If you’ve declared your variables with reasonable scopes, everything gets automatically cleaned up at the appropriate moment, no matter how you leave the block. In reply to Re^3: Set condition only if array becomes empty
by Laurent_R
|
|