How do I import environment settings into my Perl program?
#!/bin/sh
. /myfolder1/myfolder2/myScript.sh
exec perl -wxS "$0" "$@"
#!/usr/bin/perl -w
# .. the rest of your script as normal
When you run this, it will first be executed by /bin/sh
, which is capable of loading myScript.sh
into the local environment. sh
then exec
s Perl, which is told to continue from the following line.
Importing environment variables to Perl
If you want Bash to export a variable into the environment so it's accessible to programs, you can use the export
builtin:
export PRDIR
Inside Perl, you would then access it using the %ENV
hash:
my $varex = $ENV{"PRDIR"};
print "\$varex is: $varex\n";
How can I properly import the environment from running a subcommand in Perl?
I am assuming that the environment variables after program
has executed are not same as the environment passed to it (which you can find in %ENV
as explained in jeje's answer.
I am by no means knowledgeable about bash, so I am only going to address the part of the question about parsing the output of env
.
#!/usr/bin/perl
use strict;
use warnings;
use autodie qw( open close );
$ENV{WACKO} = "test\nstring\nwith\nnewlines\n\n";
my %SUBENV;
open my $env_h, '-|', 'env';
my $var;
while ( my $line = <$env_h> ) {
chomp $line;
if ( my ($this_var, $this_val) = $line =~ /^([^=]+)=(.+)$/ ) {
if ( $this_val =~ /^\Q()\E/ ) {
$var = q{};
next;
}
$var = $this_var;
$SUBENV{ $var } = $this_val;
}
elsif ( $var ) {
$SUBENV{ $var } .= "\n$line";
}
}
use Data::Dumper;
print Dumper \%SUBENV;
Importing environment variables set by batch file in parent Perl script
If your BAT file is simple (i.e. it only contains lines of the form VAR=VALUE
), you can parse it by Perl. If there is something more going on (some values are calculated from others etc.), just output all the variable names and their values at the end of the BAT script in the form VAR=VALUE
.
The parsing of the simple format is easy:
while (<$BAT>) {
chomp;
my ($var, $val) = split /=/, $_, 2;
$ENV{$var} = $val;
}
Related Topics
What Does the "Mov Rax, Qword Ptr Fs:0X28" Assembly Instruction Do
How to Store Linux Command Output into a Variable in Puppet
Setting the Thread /Proc/Pid/Cmdline
Errors While Installing Opencv and Ffmpeg Through Rightscripts
Temporarily Prevent Linux from Shutting Down
Cmake Set Environment Variable
Top Command First Iteration Always Returns the Same Result
What Is the Meaning of !#:* !#:1- in a Bash Command
Perf-Report Show Value of CPU Register
How to Check If a File Contains Only Zeros in a Linux Shell
Replace Text Based on a Dictionary
How to Do a One Way Diff in Linux
How to Configure a Specific Ip in Prometheus Yml Configuration File