my @groups; while () { chomp; next unless /\S/; if (/^#/) { push @groups, []; next; } push @{$groups[-1]}, $_; } while (@groups) { my $group = shift @groups; my $ip = splice @$group, rand @$group, 1; say $ip; push @groups, $group if @$group; } __DATA__ ... your list goes here ...