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

An easy, somewhat OT question, but I don't know where to look for an answer. I want to write something like:

#/usr/bin/perl `cd somedir`;

And have it act as though I typed it into the shell when I run the script. How does one do this? (And where should I have looked to find the answer?)

ie:

/> perl cd_script.pl /somedir/>

thanks, qq

Replies are listed 'Best First'.
Re: shell cd within perl script
by Abigail-II (Bishop) on Apr 19, 2004 at 13:58 UTC
    #!/usr/bin/perl exec "cd somedir; $ENV{SHELL}"; # Substitute if not set by your shell
    This will start a new shell though.

    Abigail

Re: shell cd within perl script
by Fletch (Bishop) on Apr 19, 2004 at 13:12 UTC

    You can't, directly. perldoc -q environment

      A FAQ, no less. Thanks. I'll wrap the perl script in a shell script or somesuch.

      qq

        Your question can be read two ways. Do you want the user's current directory to be changed after the program exits, or only during the execution of the program? Most of the answers address the latter interpretation, which is an odd requirement. Note that (as another monk has suggested) you can use chdir to change directories within the script, and it will apply to everything spawned by the script from then on, as well as to any operations the script itself does.

        The PerlMonk tr/// Advocate

        A shell script can't do it either, for much the same reason. In most shells you can use a shell function to affect the current shell's environment. If your Perl script needs to determine what directory to go to, you can just have it print that out, then use cd `your_script` in the shell function to actually change to that directory.

        For example, here's a Bash shell function using a perl script:

        function test() { cd `perl -e 'print "/tmp\n";'`; }
Re: shell cd within perl script
by guha (Priest) on Apr 19, 2004 at 13:41 UTC

    It can be done in a somewhat convoluted manner using batch file.

    Check perlrun and the - x option.

    For an applied example you could look at the code in this node.

Re: shell cd within perl script
by BUU (Prior) on Apr 19, 2004 at 13:25 UTC
    If you just want to change your "current working directory" you can use the builtin chdir, but I have no idea how to change your shells working directory.
      chdir will only have effect within the script and won't affect the shell's pwd at all. Simple example:
      perl -e "chdir('/home/username')"
Re: shell cd within perl script
by coreolyn (Parson) on Apr 20, 2004 at 14:46 UTC

    Wow! I can't believe others didn't know this one

    #! /usr/local/bin/perl -w use strict; use Cwd 'chdir'; chdir "/tmp";