use strict; use warnings; use IO::Socket::INET; sub get_sock_to_free_port { my ( $rpt_host, @rpt_ports ) = @_; foreach my $rpt_port ( @rpt_ports ) { my $sock = new IO::Socket::INET ( PeerAddr => $rpt_host, PeerPort => $rpt_port, Proto => 'tcp' ); return $sock if $sock; warn "failed check: $rpt_port - $!"; } die "No active port in list: @rpt_ports"; } my @rpt_ports = qw(12345 12346 22345 22346 22347 22348 22349 22350 22351 22352 22353 22354 22355 22356 22357 22358); my $sock = get_sock_to_free_port( '127.0.0.1', @rpt_ports ); ...