How do I carry my variables from a Bash script into a Perl one?

I have variables in a bash script that I need to be carried over into a perl one. I have the variables $gal and $obsid declared in the bash script, and then I call the new program.

gal=UCLA121
obsid=1896
./my_program

The beginning of the perl script loads an image with the phrase

$ph_im = "./$gal/img/${obsid}.img";

But the variables are NULL in the new program.

2

3 Answers

Making variables available to child process in shell script can be done either by exporting variables

export foo=bar

Or by calling program with variables prepended

foo=bar ./my_prog.pl

In either case you will need to call ENV on them inside perl script

my $barfoo = $ENV{'foo'};

Using the environment is a cleaner way.

There is the -s switch:

$ cat vars.pl
#!perl
use feature 'say';
say "foo=$foo";
say "bar=$bar";
$ echo "$foo,$bar"
123,456
$ perl -s ./vars.pl -foo="$foo" -bar="$bar"
foo=123
bar=456
2

If you are calling it like

./myscript.pl 1 35

You can use @ARGV. E.g.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
print "ARGV[0]=$ARGV[0]";
print "ARGV[1]=$ARGV[1]";
print Dumper \@ARGV;

Example source.

This is an old example, so it may not be using the latest style. I don't have a perl compiler set up at the moment, so I can't test the output.

You can use the Data::Dumper to help you debug things.

If you are calling it like

perl -s ./myprogram -$gal="$gal" -$obsid="$obsid" 1 35

Realize that you may get weird results mixing @ARGV and named parameters. You might want to change how you call it to something like

perl -s ./myprogram $gal $obsid 1 35

or

perl -s ./myprogram -gal="$gal" -obsid="$obsid" -first="1" -second="35"

Note also that the named parameters are -gal, not -$gal. I'm not quite sure what the $ would do there, but it would tend to do something other than what happens without it.

Remember, Data::Dumper can help you debug things if you get confusing results.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like