in reply to exiting a subroutine neatly

Is there a better way to execute the exit, close and then the return instead of writing them after every statement to get out of the subroutine ? kr

No

You could write <c> ... sshExitClose( $ssh ); return 2; ... sshExitClose( $ssh ); return 3; ... sub sshExitClose { $_[0]->exit_session; $_[0]->close_session; }

But thats not exactly any better than the way you have it already

Replies are listed 'Best First'.
Re^2: exiting a subroutine neatly
by SimonPratt (Friar) on May 07, 2015 at 15:10 UTC

    No

    Create the following package:

    package SSHSentry; use strict; use warnings; sub new { my ($class, %params) = @_; my $self = bless {}, $class; foreach my $func (keys %params) { next unless $self->can($func); $self->$func($params{$func}); } return $self; } sub ssh_handle { my ($self, $handle) = @_; if (defined $handle and ref $handle eq 'Net::SSH') { # Assuming Ne +t::SSH is used for ssh handle. If not, change this. $self->{ssh_handle} = $handle; } return $self->{ssh_handle}; } sub DESTROY { my $self = shift; my $ssh = $self->ssh_handle() or return; $ssh->exit_session(); $ssh->close_session(); } 1;

    Now inside your function, do something like this: my $sentry = SSHSentry->new(ssh_handle => $ssh); Once $sentry goes out of scope, DESTROY is called and your cleanup happens.

    This type of package is convenient for wrapping around all sorts of stuff that can cause big problems if your code unexpectedly dies (semaphore control in a multi-threaded environment is a big one for this). In fact, it wouldn't surprise me if there is something a bit more thorough on CPAN.