use strict; my @targets = ('10.1.1.1', '10.1.1.2', '10.2.2.1', '10.2.2.2'); my @list = intermix( @targets ); use Data::Dumper; print Dumper \@list; sub intermix { my @list = @_; my %hash; # separating hash my @ret; # returning list # build hash structure, each similar first 3 octects as key # array reference w/ IP addresses as values for (@list) { push( @{ $hash{ substr($_,0,rindex($_,'.')) } }, $_ ); } my @keys = keys %hash; while (@keys) { push(@keys, shift(@keys)); # rotate keys # extract one element, or delete the array ref and try again my $item = shift @{$hash{ $keys[0] }} || shift @keys && next; push @ret, $item; } return @ret; } __END__ $VAR1 = [ '10.1.1.1', '10.2.2.1', '10.1.1.2', '10.2.2.2' ];