e.g. my @numbers = ('1', '2', '2', '3', '3'); my @strings = ('hello', 'green', 'grass', 'rainbow', 'pretty'); my @new_strings; #### hello greengrass rainbowpretty #### for ( 0 .. $#numbers ) { push @{$h{$numbers[$_]}}, $strings[$_]; } for ( sort { $a <=> $b } keys %h ) { push @new_strings, join('', @{$h{$_}}), ">>\n"; } my $v = join ('', @new_strings); @new_strings = split (/>>/, $v); my @final_strings; for (my $k=0; $k<@new_strings; $k++) { $new_strings[$k] =~ s/\n+//g; $new_strings[$k] =~ s/\s+//g; if ($new_strings[$k] =~ /\w+/) { push @final_strings, "$new_strings[$k]"; } } #### @check = ('1','2','3','4'); # desired output: #----------------- hello greengrass rainbowpretty xxxxxxxx # THE 4TH ELEMENT NOW CONTAINS 'xxxxxxxx' as there isn't a '4' in @numbers