{ package SFTP; use IO::Handle qw( ); sub new { my $class = shift(@_); my ($to_sftp, $fr_sftp); # open2 dies on error. my $pid = open2($to_sftp, $fr_sftp, 'sftp', @_); $to_sftp->autoflush(1); return bless({ pid => $pid, to_sftp => $to_sftp, fr_sftp => $fr_sftp, }, $class); } sub DESTROY { my ($self) = @_; ...send exit command to child... ...kill child if necessary... waitpid($self->{pid}, 0); } sub do { my ($self) = @_; my $fr_sftp = $self->{fr_sftp}; my $to_sftp = $self->{to_sftp}; print $to_sftp "command"; my $response; for (;;) { my $line = <$fr_sftp>; last if $line =~ $prompt; $response .= $line; } return $response; } } my $sftp = SFTP->new(...sftp args...); my $response = $sftp->do("...\n");