use Data::Dump qw/pp/; chomp( (undef, $_, undef, @words) = <> ); # If multiple words are identical as lowercase, only the last one will be kept %restore_case = map { lc reverse, $_ } @words; $list = join '|', keys %restore_case; # Match any word in the list, only if it can be followed by words in the list until the end of the string my @result = map { $restore_case{$_} } /($list)(?=(?:$list)*$)/g; pp @result;