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

Hi, Path is not changing using system command.
#!/usr/bin/perl use Cwd; $cur_dir=getcwd(); print "Current Dir -> $cur_dir\n"; system("cd /home/sa/temp"); $new_dir=getcwd(); print "Changed path -> $new_dir\n";

Replies are listed 'Best First'.
Re: How to change path
by meraxes (Friar) on Oct 25, 2007 at 03:54 UTC

    system is executing the cd command in a forked process and returns to your Perl script. As it's happening in a different process, the working directory of your script doesn't change.

    Instead of the system call, use chdir:

    chdir '/home/sa/temp';

    update -- add links to docs
    update the second... i'm guessing the downvote was because of my erroneous description of what system was doing (as eff_i_g explains better). Fixed description to better reflect that. That'll teach me to read the docs better.

    --
    meraxes
Re: How to change path
by eff_i_g (Curate) on Oct 25, 2007 at 03:55 UTC
    Use chdir. system forks; therefore, not "saving" your cd.
Re: How to change path
by narainhere (Monk) on Oct 25, 2007 at 07:31 UTC
    This snippet
    $pwd=`pwd`; print "\n pwd is $pwd"; `cd /usr/bin`; $pwd=`pwd`; print "\n pwd is $pwd\n";
    is not changing the dir "/usr/bin" , I reason I suppose is if we execute a command directly using back-ticks(`) it will execute in a new shell.But system() will execute the commands in same shell.Am I right??

    The world is so big for any individual to conquer

      No. You're not right. 'system' forks a *new* process to execute the requested command. 'exec' would execute the command in the same process, but that would have the effect of _ending_ the Perl program to launch the new one (IOW, the program would never 'return' to the Perl program because it would _replace_ it). As someone else said, to do what the OP appears to want to do, they should use the Perl function 'chdir'.