Metacpan Download URL

This morning I read that we can now get the download URL for a CPAN module from the Metacpan API! For example, if we visit this URL

$ curl
   "download_url" : "",
   "version" : "0.096",
   "status" : "latest",
   "date" : "2016-07-03T01:36:29"

we get this blob of JSON. If we just want the URL, we could run it through jq

$ curl -s | jq .download_url

OALDERS does the same thing in Perl, but it uses three different CPAN modules. HTTP::Tiny is in the standard library, right? Oh, but it needs help from IO::Socket::SSL and Net::SSLeay to get an https URL. And we still need something to encode the URI and something to decode the JSON. Here’s my first crack at it.

#!/usr/bin/env perl

use v5.24;
use warnings;
use HTTP::Tiny;
use JSON;
use URI::Encode qw(uri_encode);

my $module = shift // die "Usage: $0 module\n";

my $uri = uri_encode("$module");

my $res = HTTP::Tiny->new->get($uri);
die "Failed!\n" unless $res->{success};

say decode_json($res->{content})->{download_url};

We didn’t need to use LWP, but we still needed help from CPAN. If we can’t do it with the standard library, why not use Mojolicous? This is a web framework, of course, but it includes some excellent client-side tools too. Here is the same thing using the Mojolicious user agent and JSON decoder.

#!/usr/bin/env perl

use v5.24;
use warnings;
use Mojo::UserAgent;

my $module = shift // die "Usage: $0 module\n";

say Mojo::UserAgent->new

We can even make it a one-liner using the delightful ojo module!

$ perl -Mojo -E 'say g("".shift)->json->{download_url}' Path::Tiny

I’m a little disappointed that it’s not easy to do something as simple as this with just the standard library, but if we use CPAN then we have lots of choices. TMTOWTDI!

Metacpan Download URL