Passing Value from Shell to Perl

Hi All,

I am calling a perl program in my shell script as follows.

MY_IN_FILE=ABC.dat
MY_OUT_FILE=XYZ.dat
MY_VARIABLE="SomeValue"

perl mycode.pl $MY_IN_FILE > $MY_OUT_FILE

Question:-
Now I want to pass value of $MY_VARIABLE from script to perl... How do I do that? Can someone please help, I'm new to perl and scripting !!

Thanks.
HCB

The four primary ways of inputting some to a program (no matter the language the program is written in)

(a) command line argument, like your file argument

(b) environment variables, typically need to export from a shell script

(c) as stdin, basically the input stream to a program

(d) as a generic file, where the program looks for well-known files.

Environment variables in perl are accessed via the $ENV list (hashed array):

# typeset -x MY_VARIABLE="SomeValue"
# perl -e 'print $ENV{"MY_VARIABLE"}'
SomeValue

Of course, you could write the whole script in perl, but...baby steps. :slight_smile:

Note that the variable(s) must be exported. I used "typeset -x" instead of "export" since I regularly typeset all the variables used in scripts. It's a good habit to adopt, since variables can be inherited if they are not typeset.

Wanna see all your scripts blow up? Try "typeset -r i" at the prompt before running them and watch what happens! This makes "$i" read only...unless the script typesets it.

I have tried
export $MY_VARIABLE

and then reading $MY_VARIABLE in perl program. I didnt get any value!

I tried as command line argument, however since I already have one file as input paramenter, it is interpreting another also as file input and I get a message that $MY_VARIABLE file does not exists.

Can you please show me syntax of passing file as one parameter and value as another parameter? or any other way?

Thanks! It worked.

I'll read further on typeset, as you mention it to be good coding habit ... and also especially after reading usage of typeset -r i

Thanks again to all who replied !

should be

export MY_VARIABLE