use Guard qw(scope_guard); sub ssh_execute_and_check { my $ssh = shift; my ($ret, $err) = $ssh->execute(@_); if ( $err or $ret =~ /Unknown command:/m ) { MyErr->throw({err => $err, ret => $ret, args => [@_]}); } return $ret; } sub foo { $ssh->start_session($ssh_host) or MyErr->throw(...); scope_guard { $ssh->exit_session; $ssh->close_session; }; my $ret1 = ssh_execute_and_check($ssh, 'command1', 'expect1'); my $ret2 = ssh_execute_and_check($ssh, 'command2', 'expect2'); ... 1; }