in reply to exiting a subroutine neatly

Try to use Guard (there are alternatives, but I'm satisfied with that one). So, your code would look like:

use Guard; # inside your routine ... my $guard = scope_guard { $ssh->exit_session; $ssh->close_session; } ... return 5;

Please note, the scope guard will be executed even if your code dies somewhere after guard definition.

WBR, basiliscos.