gwo
gwo

Reputation: 77

How can I use the Environment Modules system in Perl?

How can one use the Environment Modules system* in Perl?

Running

system("load module <module>");

does not work, presumably because it forks to another environment.


* Not to be confused with Perl modules. According to the Wikipedia entry:

The Environment Modules system is a tool to help users manage their Unix or Linux shell environment, by allowing groups of related environment-variable settings to be made or removed dynamically.

Upvotes: 4

Views: 1347

Answers (3)

Dave X
Dave X

Reputation: 5137

Alternately, to do it less perl-namespace like and more environment module shell-like, you can source the Environment Modules initialization perl code like the other shells:

do( '/usr/share/Modules/init/perl');
module('load use.own');
print module('list'); 

For a one-line example:

perl -e "do ('/usr/share/Modules/init/perl');print module('list');"

(This problem, "source perl environment module" uses such generic words, that it is almost un-searchable.)

Upvotes: 3

ThisSuitIsBlackNot
ThisSuitIsBlackNot

Reputation: 24073

It looks like the Perl module Env::Modulecmd will do what you want. From the documentation:

Env::Modulecmd provides an automated interface to modulecmd from Perl. The most straightforward use of Env::Modulecmd is for loading and unloading modules at compile time, although many other uses are provided.

Example usage:

 use Env::Modulecmd { load => 'foo/1.0' };

Upvotes: 4

ikegami
ikegami

Reputation: 386361

system("load module foo ; foo bar");

or, if that doesn't work, then

system("load module foo\nfoo bar");

I'm guessing it makes changes to the environment variables. To change Perl's environment variables, it would have to be executed within the Perl process. That's not going to work since it was surely only designed to be integrated into the shell. (It might not be too hard to port it, though.)

If you are ok with restarting the script after loading the module, you can use the following workaround:

use String::ShellQuote qw( shell_quote );

BEGIN {
   if (!@ARGV || $ARGV[0] ne '!!foo_loaded!!') {
      my $perl_cmd = shell_quote($^X, '--', $0, '!!foo_loaded!!', @ARGV);
      exec("load module foo ; $perl_cmd")
         or die $!;
   }

   shift(@ARGV);
}

Upvotes: -1

Related Questions