/lib/WWW/Search/DuckDuckGo.pm

https://github.com/trapd00r/WWW-Search-DuckDuckGo · Perl · 117 lines · 26 code · 12 blank · 79 comment · 2 complexity · 46ffbfa3b4527fd3633e0efebe4124e5 MD5 · raw file

  1. package WWW::Search::DuckDuckGo;
  2. $VERSION = '0.001';
  3. require Exporter;
  4. @ISA = 'Exporter';
  5. our @EXPORT_OK = qw(ddg);
  6. use strict;
  7. use Carp qw(croak);
  8. use JSON::XS;
  9. use LWP::UserAgent;
  10. my $base_url = 'http://api.duckduckgo.com/?q='; # $query&o=json
  11. sub ddg {
  12. my $query = shift // 'perl';
  13. my $u = LWP::UserAgent->new;
  14. my $response = $u->get( _full_url($query) );
  15. if($response->is_success) {
  16. return decode_json( $response->content );
  17. }
  18. else {
  19. croak($response->status_line);
  20. }
  21. }
  22. sub _full_url {
  23. my $query = shift;
  24. return $base_url . $query . '&o=json';
  25. }
  26. =pod
  27. =head1 NAME
  28. WWW::Search::DuckDuckGo - search DuckDuckGo
  29. =head1 SYNOPSIS
  30. use WWW::Search::DuckDuckGo;
  31. my $results = ddg('perl');
  32. =head1 DESCRIPTION
  33. B<WWW::Search::DuckDuckGo> provides a simple interface for searching with
  34. DuckDuckGo.
  35. =head1 EXPORTS
  36. None by default.
  37. =head1 FUNCTIONS
  38. =head2 ddg()
  39. Parameters: $query
  40. Returns: \%results
  41. my $results = ddg('laleh');
  42. The main search function. Returns a data structure that might look something
  43. like this:
  44. Abstract => "Laleh Pourkarim is an Iranian-Swedish singer-songwriter and former actress. ",
  45. AbstractSource => "Wikipedia",
  46. AbstractText => "Laleh Pourkarim is an Iranian-Swedish singer-songwriter and former actress. ",
  47. AbstractURL => "http://en.wikipedia.org/wiki/Laleh",
  48. Answer => "",
  49. AnswerType => "",
  50. Definition => "",
  51. DefinitionSource => "",
  52. DefinitionURL => "",
  53. Heading => "Laleh",
  54. Image => "http://i.duck.co/i/eb3ccaa1.jpg",
  55. RelatedTopics => [
  56. {
  57. FirstURL => "http://duckduckgo.com/c/Swedish_people_of_Iranian_descent",
  58. Icon => {},
  59. Text => "Swedish people of Iranian descent Category"
  60. },
  61. ],
  62. Results => [
  63. {
  64. FirstURL => "http://www.laleh.se/",
  65. Icon => {
  66. Height => 16,
  67. URL => "http://i.duck.co/i/laleh.se.ico",
  68. Width => 16
  69. },
  70. Result => "<a href=\"http://www.laleh.se/\"><b>Official site</b></a>",
  71. Text => "Official site"
  72. }
  73. ],
  74. =head1 AUTHOR
  75. Magnus Woldrich
  76. CPAN ID: WOLDRICH
  77. magnus@trapd00r.se
  78. http://japh.se
  79. =head1 COPYRIGHT
  80. Copyright 2011 Magnus Woldrich <magnus@trapd00r.se>. This program is free
  81. software; you may redistribute it and/or modify it under the same terms as
  82. Perl itself.
  83. =cut
  84. 1;