#!/usr/bin/perl use strict; use WWW::Mechanize; use JSON -support_by_pp; my $query = "Democratic Republic of Congo"; my $api_key = "YOUR KEY HERE"; my $year = "1981"; while ($year <= 2009) { my $count = fetch_json_page('http://api.nytimes.com/svc/search/v1/article?query=' . $query . '&api-key=' . $api_key . '&facets=publication_year&begin_date=' . $year . '0101&end_date=' . $year . '1231&fields=title'); print $year . "\t" . $count . "\n"; $year++; } sub fetch_json_page { my ($json_url) = @_; my $browser = WWW::Mechanize->new(); my $count; eval{ $browser->get( $json_url ); my $content = $browser->content(); my $json = new JSON; my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content); foreach my $chunk(@{$json_text->{facets}->{publication_year}}){ $count = $chunk->{count}; } }; if($@){ print "[[JSON ERROR]] JSON parser crashed! $@\n"; } return $count || 0; }