How to get the Perl command line to accept shell variables?

I can do the math like

perl -e 'print 5253413/39151' -l 

But I don’t quite understand how to use Perl's ability to do the math with my predefined bash variables. I tried

 var1=$(some wc command that yields a number); var1=$(some wc that yields another number) perl -e 'print var1/var2' -l 

But it does not work

+5
source share
2 answers

There are two main ways to do this.

  • In Perl code, you can use the %ENV built-in hash to access environment variables 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 tool to insert the value of the shell variable into the command

    This is best used as parameters for single-line perl rather than entering values ​​directly into the code.

     $ var1=5253413 $ var2=39151 $ perl -E '($v1, $v2) = @ARGV; say $v1/$v2' $var1 $var2 134.183366963807 
+11
source

Two less common ways to do this use the long-standing perl functions.

The first is the main Env module , which associates work environment variables with 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 variables must be present in the environment inherited by the perl process, for example, export VAR , as described above, or explicitly for a single command (as in FOO=hello perl -MEnv -E 'say $FOO' ).

A second and more obscure way is to use perl -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 .

+6
source

Source: https://habr.com/ru/post/1240887/


All Articles