in reply to
General pattern for interactive text-mode script?
If you want to keep your sanity while programming, you'll encode all of the nesting logic into a data structure, and all the code blocks marked with #... in your example into a dispatch table.
Then you write a small dispatching program that walks through the data structure, prints the prompt, analyses the results, makes a transition into the next state and calls your callback (maybe in a different order).
Searching cpan for state might give some interesting results, chances are that somebody already implemented something similar.