Importing environment variables to Perl

后端 未结 3 1209
甜味超标
甜味超标 2021-01-15 03:33

I\'m not sure if importing is the right word to use. I\'m a beginner in both Perl and Bash. I have set a variable on Bash, so when I do:

echo $PRDIR
         


        
相关标签:
3条回答
  • 2021-01-15 03:55

    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";
    
    0 讨论(0)
  • 2021-01-15 03:58

    Another solution to use the variable directly in perl :

    In the shell :

    $ export PRDIR=foobar
    

    In perl :

    #!/usr/bin/perl
    
    use Modern::Perl;
    
    use Env qw/PRDIR/;
    
    say $PRDIR;
    
    0 讨论(0)
  • 2021-01-15 04:00

    I guess you need something like this:

    use Cwd 'abs_path';
    use File::Basename;
    my $self = abs_path($0);
    my $bindir = dirname( abs_path($0) );
    unless ($ENV{APP_ENV}) {
        warn "No APP_ENV, will try to get from bin/env.sh";
        exec("source $bindir/env.sh && /usr/bin/perl $self") || die "$!";
    }
    

    I have env.sh in my bin folder with following content:

    export APP_ENV=development
    

    The idea behind this approach is that I don't need to bother if I set my ENV variables before running my Perl code or forget to do it. I need just to run my Perl program and it will take care about preparing environment for itself.

    0 讨论(0)
提交回复
热议问题