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

Hi, From the below code I'm unable to change the directory to the specified one. Even after executing the directory is not changed(i used the command 'pwd'). Can some one help!

#!/usr/bin/perl
#!/usr/bin/perl
use strict;
use warnings;


my $ChandeDir = "cd \/usr\/local\/ebs\/uninstall\/";
system(`$ChandeDir`)

Replies are listed 'Best First'.
Re: System Command - Change Dir
by holli (Abbot) on Aug 25, 2008 at 07:16 UTC
    Actually the directory is changed, but you don't notice because you are shelling out. That means your code starts a shell, changes the directory within that shell and then the shell exits. That's not what you want.

    Use the builtin function chdir. That changes the cwd of the running script. (see perlfunc)


    holli, /regexed monk/
Re: System Command - Change Dir
by tilly (Archbishop) on Aug 25, 2008 at 07:16 UTC
    Short answer, use chdir and your problem goes away. You're not doing error checking as perlstyle indicates, and that hides additional errors.

    Here is a fuller explanation. The system command creates a new process that does something then exits. So if you have a system command that does a cd, the child process does a CD and goes bye bye. Which leaves the Perl process still in the original directory.

    Actually it is a little worse than that. You're using both backticks and system. So you execute the command using backticks, and then the return from that (an empty string) is passed to system. Which then fails but you don't notice because you're not doing any error checking.

    Anyways you need the changing directory to happen in the Perl process, and not in a temporary process that goes away. And that is why you have to use the built-in chdir instead.

Re: System Command - Change Dir
by lima1 (Curate) on Aug 25, 2008 at 07:18 UTC
    You don't have to quote the slashes. But why don't you use the chdir function? Example from die
    chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"
      Thanks ALL It worked.