20091207 sourcing an env file from within perl - plembo/onemoretech GitHub Wiki

title: Sourcing an .env file from within perl link: https://onemoretech.wordpress.com/2009/12/07/sourcing-an-env-file-from-within-perl/ author: lembobro description: post_id: 210 created: 2009/12/07 20:07:36 created_gmt: 2009/12/07 20:07:36 comment_status: open post_name: sourcing-an-env-file-from-within-perl status: publish post_type: post

Sourcing an .env file from within perl

There’s lots of suggested solutions for this one all over the Internet. But that, as usual, is the problem. If you haven’t already guessed, the need to do this is an Oracle-driven thing. System administration of Oracle stuff invariably requires the “sourcing” of an environment file to set the system environment for some executable or script. Without adding module support for more sophisticated shell operations (e.g. Shell::Source), you’re going to have to use one of a number of methods to get there. Unfortunately most of those called upon to help out with this kind of problem have trouble with accepting it’s a necessary task (”Why do you want to do this?”), and so their solutions wind up being typically perlish and therefore … inelegant.

Here’s the scoop. To source an .env file and suck its results into your script, use an eval statement like this (where $envfile is a variable representing the full name and path of your .env, like “$HOME/oracle.env”):
`

eval {
        exec ". $envfile; /usr/bin/perl -s $0 -env -- @ARGV";
} unless $env;

`

What this snippet does is set up an “-env” switch (defined by the “-s” option) that consists of the results flowing from the sourcing of $envfile. The “unless $env” prevents the script from going into an infinite loop. If you use the “strict” pragma, be sure to place this eval statement (and anything it depends on) above “use strict;”. Very clever, and something I could never have thought up on my own.

Here’s a different approach that requires some heavier lifting.

Copyright 2004-2019 Phil Lembo