#!/usr/bin/env perl

=head1 NAME

ddg.pl -- Query the Duck Duck Go search engine.

=head1 SYNOPSIS

In the shell:

   $ ddg.pl duck duck go
   $ ddg.pl '!date longcat'

Or in your program:

   do 'ddg.pl';
   my $result = ddg($query);

=cut

use JSON::PP;
use HTTP::Tiny;

sub ddg
{
   my $q = shift;
   my $h = HTTP::Tiny->new;
   my $res = $h->get(
       'http://api.duckduckgo.com/?format=json&q='
           . $h->www_form_urlencode({
               format => 'json',
               q => $q
           }));
   die unless $res->{success};
   $res = decode_json($res->{content});
   for (keys %$res) {
       delete $res->{$_} if $res->{$_} eq '';
   }
   $res;
}

if (!defined caller) {
   eval 'use Data::Dumper';
   print Dumper(ddg("@ARGV"));
}

__END__

=head1 DESCRIPTION

C<ddg.pl> provides basic access to the Duck Duck Go search engine API.
It supplies a single function, C<ddg>, which takes a query string and
returns the API result as a hash reference.  It has no non-core
dependencies on Perl 5.14 or newer, and requires only L<HTTP::Tiny>
and L<JSON::PP> on older Perls.

=head1 SEE ALSO

The Duck Duck Go API page, L<http://duckduckgo.com/api.html>.

L<WWW::DuckDuckGo>, a heavier and more full-featured module.

L<App::DuckDuckGo>, a heavier command-line program.

=head1 AUTHOR

Sean O'Rourke, E<lt>[email protected]<gt>

Bug reports welcome, patches even more welcome.

=head1 COPYRIGHT

Copyright (C) 2012 Sean O'Rourke.  All rights reserved, some wrongs
reversed.  This module is distributed under the same terms as Perl
itself.

=cut