vladb has asked for the wisdom of the Perl Monks concerning the following question:

For one application I'm looking at, I have to modify it so that it sets initial shell PWD to a path of it's choosing. For example, if you were to launch the script inside /usr/bin/foobar.pl

it would drop you to /usr/some/other/path. Kind of like doing 'cd /usr/some/other/path' right after the process is done executing.

Is there any way I could do it (from Perl script...). Here's what I've played with:
use strict; my $path = shift || $ENV{HOME}; print "will cd to '$path'\n"; # these both won't work (obviously ;-) #$ENV{PWD}=$path; #chdir($path); # changes this process' directory.
Thanks for help in advance ;).

"There is no system but GNU, and Linux is one of its kernels." -- Confession of Faith

Replies are listed 'Best First'.
Re: Changing shell path inside perl script.
by Juerd (Abbot) on Jan 09, 2002 at 07:14 UTC
    From perlfaq8:

    I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?

    Unix

      In the strictest sense, it can't be done--the script executes as a different process from the shell it was started from. Changes to a process are not reflected in its parent--only in any children created after the change. There is shell magic that may allow you to fake it by eval()ing the script's output in your shell; check out the comp.unix.questions FAQ for details.

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: Changing shell path inside perl script.
by metadoktor (Hermit) on Jan 09, 2002 at 18:14 UTC
    If I understand what you are asking, you want to know how to change the directory within perl and maintain that change once you've exited the script?

    You likely cannot do this, since as the previous poster stated, because changes in a child process are not maintained in the parent; however, instead of trying to beat your head against the wall why not add a simple function to your .profile login script?

    function mycd
    {
         cd /to/your/new/path
    }
    
    then you could issue the following command at the UNIX prompt:
    /usr/bin> mycd
    /to/your/new/path>
    

    or you could create a shell script and place it in a directory that is in your PATH.

    #!/bin/ksh
    cd /to/your/new/path
    
    or if you're under Microsoft Windows you can create a mycd.bat file and place it in a directory that is in your PATH.
    cd /to/your/new/path
    

    metadoktor

    "The doktor is in."