my $connection; while(1) { # the connect method either returns a valid connection object or undef, ERR_MSG print "Trying to connect....."; ($connection, my $error) = connect(); if ( $connection ) { print "Connected OK!\n"; last; } else { print "Connect failed error: $error, retry in 5 sec.\n"; sleep 5; } } # now do stuff with your $connection