2

I'm having a bit of trouble understanding why a csh command to source a file works fine from the command line but fails to work when incorporated into a Perl script.

  my @envvar = ();
  if (-e $ENV{WSDIR}."/<script>.csh") {
    @envvar = `csh -c "cd $WSDIR ; source <script>.csh  ; env"`;
  }

When run I the Perl script I get an error as follows script.csh: No such file or directory, whereas running from the terminal as a csh command works as expected. What is the limitation on using environment variables in a csh command within Perl? How do I overcome this issue.

2
  • 4
    Always use use strict; use warnings;! It would have caught this. Commented Feb 27, 2013 at 16:01
  • And for the backticks - I always avoid them and use qx(csh...) instead; much more readable to me. Commented Feb 27, 2013 at 20:34

2 Answers 2

6

$WSDIR is being interpolated to the empty string by perl. You need to escape the '$' so that it is sent to the shell, which can expand $WSCIR as desired.

@envvar = `csh -c "cd \$WSDIR ; source <script>.csh  ; env"`;

or you can let perl expand the environment variable itself:

@envvar = `csh -c "cd $ENV{WSDIR} ; source <script>.csh  ; env"`;
Sign up to request clarification or add additional context in comments.

Comments

1

When perl gets started it makes it own sub shell. That sub shell does not contain all features like sourcing a shell file which are available only for main shells.

You can do this by installing external module from CPAN which is Shell::Source

$env_path= Shell::Source->new(shell=>"tcsh",file=>"../path/to/file/<script>.csh");
$env_path->inherit;
print "Your env path: $ENV{WSDIR}";

As perl creates its own instance while running on a shell, so we can not set environment path for the main shell as the perl's instance will be like sub shell of the main shell. Child can not set environment paths for parents.

Now till the perl's sub shell will run you'll be able to access all the paths present in your .csh

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.