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