http://qs321.pair.com?node_id=1178285

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

Hi Monks,

I want to change the directory, but this change should be valid even after ending the script.

In the example given the script changes the directory to ".." and shows the content. But after ending the script I am back in the directory where I started the example and not in ".."

Is there a way that the script changes the directory not "locally" ?

many thanks

#!/usr/bin/perl system ("cd .."); system ("ls");

Replies are listed 'Best First'.
Re: change directory
by Corion (Patriarch) on Dec 21, 2016 at 10:35 UTC

    That's not how the "current directory" works. The "current directory" is a property of the currently running process. If you want to change the current directory of the parent process, you need cooperation of the parent process.

    A common approach is to output shell commands from your script and have the shell run these commands:

    #!perl -w print "cd ..\n";
    > eval "$(myscript.pl)"
Re: change directory
by hippo (Bishop) on Dec 21, 2016 at 10:39 UTC
Re: change directory
by choroba (Cardinal) on Dec 21, 2016 at 11:56 UTC
    > Is there a way that the script changes the directory not "locally" ?

    chdir

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: change directory
by CountZero (Bishop) on Dec 21, 2016 at 15:29 UTC
    What do you mean by
    after ending the script I am back in the directory where I started the example
    ?

    Did you start your program from the command line and you expected upon ending the script to find yourself in another directory?

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics

      Yes. Thats what I tried to do. Starting the perl script, and after the perl script is finished, I am in a different directory.

      The perl script does much more, but the chdir function I am not able to realise.