in reply to Re: exiting a subroutine neatly
in thread exiting a subroutine neatly
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.
|
|---|