sub choose_host { my $chosen_host; while ( !defined $chosen_host ) { printchoices(); $chosen_host = hostname_by_num( getchoice() ); } return $chosen_host; } # for loop can now be: sub printchoices { print join "\n", "\n", "ssh hosts", "-"x8; foreach my $host_num ( 1..num_hosts() ) { print "[$host_num] ", hostname_by_num($host_num), "\n" ; } }