use Data::Dumper; my @file1 = split "\n", <<_FILE1_; # I can't have two __DATA__ sections in the same file so here goes the first one ldt b05dcc00 mny b05can03*n0b5 b05mdd04*n9c9 _FILE1_ my @regexen; # Ordered list of search patterns for (@file1) { next unless m<\S>; # skip the blank lines s<\*><\\w*>g; # the * becomes \w* which means "any number of alphanum chars or _" push @regexen, $_; # we push the pattern at the end of the list } my %result; while () # for each line of file 2 { for $search (@regexen) # for each search pattern { push @{ $result{$search} }, $1 if /\b(\w*$search\w*)\b/; # we push the line at the end of the matches of $search if it matches } } # let's print the result ! for $key (@regexen) # for each search pattern, in the right order { for $line (@{ $result{$key} }) # for each line this search pattern matched { print $line, "\n"; # we print it } } __DATA__ /* To start: b05afn10ud0b0 */ /* To start: b05dcc00ud0c0 */ /* To start: b05ldt10ud0e0 */ /* To start: b05dcc10ud0i0 */ /* To start: b05afn10ud0m0 */ /* To start: b05afn10ud0s0 */ /* To start: b05mny00ud0b5 */ /* To start: b05mny00ud0d3 */ /* To start: b05mdd04un9c9 */ /* To start: b05ahn00ud0j5 */ /* To start: b05mny00ud0m7 */ /* To start: b05can03un0b0 */ /* To start: b05can03un0b5 */