my @terms = qw( foo bar baz fool foolish ); my $re = join '|', map{quotemeta} sort {length($b)<=>length($a)}@terms; $re = qr/($re)/; while(){ my @matches = $_ =~ m/$re/g; next unless @matches; print "Got @matches\n" } __DATA__ Only a foobar foolish fool skips the sort by length Without this foo you look foolish and may match short elements!