2

I have a shell script (csh) calling Perl like this:

set SHELL_VAR = "foo"
set RES = `perl -e 'my $perl_var = uc("$SHELL_VAR"); print "$perl_var\n"'`
echo $RES

I did not manage to use single or double quotes properly, no matter which combination I tried.

How do I properly mix variables in Perl and shell?

Both are starting with $. Double quotes use variable values, but returns

error perl_var: Undefined variable.

in shell. Enclosing a Perl script by single quotes led to an empty result. Escaping like \$perl_var does not succeed either.

3
  • have you tried using escape "\" for it? Commented Jun 5, 2014 at 11:44
  • 3
    See Csh Programming Considered Harmful, especially the section 4. QUOTING. Commented Jun 5, 2014 at 11:51
  • @NoobEditor: Yes, I tried it as mentioned in question Commented Jun 5, 2014 at 13:22

3 Answers 3

2

You are trying to insert the value of a shell var into a Perl literal of a program that's in a command line. That's two levels of escaping! Instead, just pass it to Perl as an argument.

% set SHELL_VAR = "foo"
% set RES = `perl -e'print uc($ARGV[0])' "$SHELL_VAR"`
% echo "$RES"
FOO

Doh! It's not quite right.

csh% set SHELL_VAR = foo\"\'\(\ \ \ \$bar
csh% set RES = `perl -e'print uc($ARGV[0])' "$SHELL_VAR"`
csh% echo "$RES"
FOO"'( $BAR

I should get

FOO"'(   $BAR

In sh, I'd use RES="` ... `" aka "$( ... "), but I don't know the csh equivalent. If someone could fix the above so multiple spaces are printed, I'd appreciate it!

sh$ shell_var=foo\"\'\(\ \ \ \$bar
sh$ res="$( perl -e'print uc($ARGV[0])' "$shell_var" )"
sh$ echo "$res"
FOO"'(   $BAR
Sign up to request clarification or add additional context in comments.

Comments

1

You can push your SHELL_VAR into the environment and let Perl pull it from there:

#!/bin/csh
setenv SHELL_VAR "foo"
set RES = `perl -e 'my $perl_var = uc($ENV{SHELL_VAR}); print "$perl_var\n"'`
echo $RES

Note that the setenv command lacks the expicit '=' for assignment. The environmental variable is availab e to Perl from the %ENV hash with the variable name as its key.

Comments

0

I found another solution, you can simply concatenate several expressions, i.e. you can write

set XYZ = "foo"`date`bar$HOST'gugus'

for example. This is a concatenation of

foo + `date` + bar + $HOST + gugus

Thus the following works:

set SHELL_VAR = "foo"
set RES = `perl -e 'my $perl_var = uc("'$SHELL_VAR'"); print "$perl_var\n"'`
echo $RES

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.