use strict; use warnings; use 5.010; use List::Util qw(max); my @letters = ('a' ... 'z', (' ') x 5); my %words = map { join('', map { $letters[int rand(@letters)] } 1 .. max(5, rand(50))) => $_ } 1..5_000; my @keys_sorted_by_length_desc = sort { length $b <=> length $a } keys %words; my $re = join '|', @keys_sorted_by_length_desc; $re = qr{($re)}i; while (<>) { chomp; if ($_ =~ $re) { say "found match $1 in '$_', $words{$1}"; } }