PageRenderTime 94ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/DDG/Goodie/TitleCase.pm

https://gitlab.com/0072016/zeroclickinfo-goodies
Perl | 45 lines | 32 code | 11 blank | 2 comment | 5 complexity | 60f9835a00892905e4fa3d11f604e945 MD5 | raw file
  1. package DDG::Goodie::TitleCase;
  2. # ABSTRACT: Convert a string to title case.
  3. use DDG::Goodie;
  4. triggers startend => 'titlecase', 'ucfirst', 'title case', 'capitalize';
  5. primary_example_queries 'titlecase test';
  6. description 'return the query in title case';
  7. name 'Title Case';
  8. code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/TitleCase.pm';
  9. category 'transformations';
  10. topics 'words_and_games';
  11. attribution github => ['https://github.com/moollaza', 'moollaza'],
  12. github => ['https://github.com/maxluzuriaga', 'Max Luzuriaga'];
  13. zci is_cached => 1;
  14. zci answer_type => "title_case";
  15. # http://blog.apastyle.org/apastyle/2012/03/title-case-and-sentence-case-capitalization-in-apa-style.html
  16. my @exceptions = ("a", "an", "and", "the", "by", "but", "for", "or", "nor", "yet", "so", "as", "at", "in", "of", "on", "per", "to");
  17. handle remainder => sub {
  18. return unless $_;
  19. my @words = split(/ /, $_);
  20. @words = map {
  21. my $word = $words[$_];
  22. if ($_ == 0) {
  23. ucfirst $word # Capitalize first word
  24. } else {
  25. if (grep { $_ eq $word } @exceptions) {
  26. $word # Don't capitalize minor words
  27. } else {
  28. join('-', map { ucfirst $_ } split(/-/, $word) ) # Capitalize every part of a hyphenated word
  29. }
  30. }
  31. } 0 .. $#words;
  32. return join(' ', @words);
  33. };
  34. 1;