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

hi all! well, if I try:
system("cd",$somePath);
when the script finishes, I'm not in the directory that perl changed to. I know this is normal, but is there any way to actually cd from within a perl script? thanx

Replies are listed 'Best First'.
Re: cd?
by chromatic (Archbishop) on Feb 06, 2002 at 02:15 UTC
    This is a question in perlfaq8 (but it's not immediately obvious, so this is not a lecture :). If chdir doesn't help, you can replace the running process with judicious use of exec.
Re: cd?
by dws (Chancellor) on Feb 06, 2002 at 01:51 UTC
    You can chdir($somePath) from within a script, but the effect is temporary. There is no easy way to side-effect the cd'ness of the environment that the script was invoked from.

Re: cd?
by rjray (Chaplain) on Feb 06, 2002 at 02:02 UTC

    This is the way processes work. Observe the following Bourne shell script:

    : cd $* pwd

    Make that into an executable script, and call it with a directory argument. You'll see from the output of pwd that the script is now in the requested subdirectory. But when the script has finished executing, run pwd yourself and you will see that you are still where you started out from.

    --rjray

Re: cd?
by jmcnamara (Monsignor) on Feb 06, 2002 at 09:09 UTC

    As the others have pointed out the shell doesn't work like that. A possible workaround is to alias the output of the program to a command:
    #!/usr/bin/perl -w use strict; my $dir = '/usr/bin'; if (chdir $dir) { print $dir; } else { print STDERR "Couldn't cd to $dir\n"; print '.'; } __END__ Then in your shell set an alias: alias mycd='cd `perl mycd.pl`'

    --
    John.