当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - How do I get command-line Perl to accept shell variables?

问题描述:

I can do math like

perl -e 'print 5253413/39151' -l

But I don't quite get how to take advantage of Perl's ability to do math with my own predefined bash variables. I've tried

var1=$(some wc command that yields a number); var1=$(some wc that yields another number)

perl -e 'print var1/var2' -l

But it doesn't work

网友答案:

There are two main ways to do this.

  • Within the Perl code you can use the %ENV built-in hash to access environment variables that are exported from the shell

    $ export var1=5253413
    $ export var2=39151
    $ perl -E 'say $ENV{var1}/$ENV{var2}'
    134.183366963807
    
  • You can use the shell interpolation facility to insert the value of a shell variable into a command

    This is best done as parameters to the perl one-liner rather than introducing the values directly into the code

    $ var1=5253413
    $ var2=39151
    $ perl -E '($v1, $v2) = @ARGV; say $v1/$v2' $var1 $var2
    134.183366963807
    
网友答案:

Two less common ways to do this make use of long-standing perl features.

The first is the core module Env, which ties process environment variables to perl variables:

sh$ export VAR1=1000
sh$ export VAR2=33
sh$ perl -MEnv -E 'say $VAR1/$VAR2'           # imports all environ vars
333.333333333333
sh$ perl -MEnv=VAR1,VAR2 -E 'say $VAR1/$VAR2' # imports only VAR1, VAR2
333.333333333333

Note that the variables need to be present in the environment inherited by the perl process, for example with export VAR as above, or explicitly for a single command (as by FOO=hello perl -MEnv -E 'say $FOO').

The second and rather more obscure way is to use use perl's -s switch to set arbitrary variables from the command line:

sh$ VAR1=1000
sh$ VAR2=33
sh$ perl -s -E 'say $dividend/$divisor' -- -dividend=$VAR1 -divisor=$VAR2
333.333333333333

awk does something similar with its -v switch.

分享给朋友:
您可能感兴趣的文章:
随机阅读: