#!/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__ # Hacked by usemodperl: use Carp. Added module cache. use strict; use warnings; use Carp 'croak'; 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 { local ($_) = @_; if (/install the (\S+) module/) { my $module = $1; my $moddir = '.perlmod'; (my $modloc = $module) =~ s/::/__/g; $modloc = "$moddir/$modloc"; if (-d $moddir and -e $modloc) { open my $fh, '<', $modloc or croak "$!"; @_ = <$fh>; close $fh; $_ = join "\n", @_; eval $_ or croak; } else { require HTTP::Tiny; $_ = HTTP::Tiny->new->get("https://metacpan.org/pod/$module"); croak unless $_->{content}; for ($_->{content} =~ /Source<\/a>\s*\(raw/) { $_ = HTTP::Tiny->new->get($1); $_ = $_->{content} ? $_->{content} : croak; eval $_ or croak; eval mkdir $moddir; croak $@ if $@; if (open my $fh, '>', $modloc or croak "$!") { print $fh $_; close $fh; } last } } } }