in reply to exiting a subroutine neatly
Generically speaking, I think that this is an excellent opportunity to use “exceptions.”
Basically, you arrange for some wrapper routine to take care of the protocols of initiating the SSH session, and of ending it. “In the meantime, it calls your routine.” If everything goes splendidly, your routine will return. But, if “Private SNAFU was here,” your routine will instead throw an exception ... in Perl-speak, it will die. And if this happens, the outer-level “wrapper” routine will catch that exception ... in Perl-speak, eval { }. Either way, the outer-level routine is firmly in control.
Thus, your handler-routine has a very simple job-description: “Try your best to do what you’ve been asked to do, but if you find that you cannot do it, die.”
And, the outer-level routine that called your handler has a simple job-description, too: “Hope that the routine returns, but be prepared for the possibility that he won’t. No matter what happens, see to it that the ssh session is properly initiated and terminated.”