#!/usr/bin/perl -l # Use a CPAN module that is *not* installed! Is this a good idea? # Posted to perlmonks.org by an Anonymous Monk on Sun Jun 17 2018 # # In this example, if the Astro::MoonPhase module is not installed, # the use_cpan sub will parse the error, download the module page # from metacpan, parse that for the source code uri, download the # raw module source, eval that string, and proceed normally as if # the module was installed! It does not work with all modules and # the concept is presented to the Monastery for contemplation. #__QKB__ use strict; use warnings; eval { require Astro::MoonPhase }; use_cpan($@) if $@; my @phases = Astro::MoonPhase::phasehunt(); print q~LOCALTIME = ~, scalar localtime time; print q~New Moon = ~, scalar localtime $phases[0]; print q~First quarter = ~, scalar localtime $phases[1]; print q~Full moon = ~, scalar localtime $phases[2]; print q~Last quarter = ~, scalar localtime $phases[3]; print q~New Moon = ~, scalar localtime $phases[4]; sub use_cpan { my ($module) = @_; if ($module =~ /install the (\S+) module/) { my $modname = $1; require HTTP::Tiny; my $pm = HTTP::Tiny->new->get("https://metacpan.org/pod/$modname"); for ($pm->{content} =~ /Source<\/a>\s*\(raw/) { $pm = HTTP::Tiny->new->get($1); eval $pm->{content}; last } } }