I know there's a heck of a lot to be learnt from rolling your own, but in such circumstances as you have here, IMO, you'd be better
useing (once again, pun intended:-)
Net::SSH since it already has covered the problem(s) of interaction with the remote shell...
A user level that continues to overstate my experience :-))