Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Install and then load missing modules with in a script

by edimusrex (Monk)
on Jul 20, 2016 at 18:16 UTC ( #1168165=perlquestion: print w/replies, xml ) Need Help??

edimusrex has asked for the wisdom of the Perl Monks concerning the following question:

I am not sure if what I am attempting is possible but I'll ask any ways. I have a script which performs various checks. This script will be deployed on at least 6 servers. Currently I only require it to use 2 modules, DateTime and DBI; The idea is that it will first check to see if those modules are indeed installed and if they are not, install and load them. I am looking into Module::Load but not sure if it can handle what I am trying to accomplish. I'd prefer not to use a module to do this. What I currently have is the following

#!/usr/bin/perl use warnings; use strict; my $version = `cat /etc/*-release | head -n 1`; chomp $version; my ($os) = $version =~ /(Ubuntu|CentOS)/; my %rhel = ( "DBI" => "perl-Class-DBI-mysql.noarch", "DateTime" => "perl-DateTime.x86_64", ); if ($os eq 'CentOS'){ foreach my $mod (keys %rhel){ eval { require $mod; $mod->import(); 1; } or do { system("yum install $rhel{$mod} -y"); } } }

2 issues with this, 1 it does not actually seem to load the module and 2 I don't want the text in STDOUT from the eval.

If any of this makes any sense and you can help I'd love the advice. Thanks in advance


------ UPDATE ------

Seems like I have solved my issue. Here is what I ended up doing

#!/usr/bin/perl use warnings; use strict; my $version = `cat /etc/*-release | head -n 1`; chomp $version; my ($os) = $version =~ /(Ubuntu|CentOS)/; my %rhel = ( "DBI" => "perl-Class-DBI-mysql.noarch", "DateTime" => "perl-DateTime.x86_64", ); if ($os eq 'CentOS'){ foreach my $mod (keys %rhel){ eval "use $mod"; if($@){ system("yum install $rhel{$mod} -y"); eval "use $mod"; } } }

Thanks for the help

Replies are listed 'Best First'.
Re: Install and then load missing modules with in a script
by dmitri (Priest) on Jul 20, 2016 at 19:33 UTC
    I see two issues:
    1. You're looking for eval "require $mod";. See perldoc -f require for more info.
    2. Thinko: after system() call (whose return value you should check, btw), you need to require the module you just installed.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1168165]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2021-09-19 15:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?