tokuhirom's Blog

cpan-get command to fetch CPAN module tar ball

Here is a code:

#!/usr/bin/perl
use strict;
use warnings;
use HTTP::Tiny;
use File::Basename qw(basename);

my $pkg = shift or die "$0 Module::Name\n";
$pkg =~ s!-!::!g;

my $http = HTTP::Tiny->new;
my $res = $http->get("http://cpanmetadb.plackperl.org/v1.0/package/$pkg");
die "Failed! $res->{status}: $res->{reason}\n" unless $res->{success};
if ($res->{content} =~ /distfile: (.*)/) {
    my $url = "http://cpan.metacpan.org/authors/id/$1";
    my $file = basename($url);
    my $res = $http->mirror($url, $file);
    if ( $res->{success} ) {
        print "Fetched $file\n";
    } else {
        die "Cannot retrieve file from $url: $res->{status}: $res->{reason}";
    }
}

You can run this code by following:

% cpan-get Time::Piece
Fetched Time-Piece-1.22.tar.gz

Enjoy!

[Updated]

$pkg =~ s/-/::/g;

Suggested by hirose31++

And so