perl function chdir
In Perl, the chdir
function is used to change the current working directory. It takes a single argument, which is the path to the new working directory.
Here's an example that demonstrates the use of the chdir
function:
use strict; use warnings; # get the current working directory my $cwd = `pwd`; print "Current directory: $cwd\n"; # change the working directory chdir('/tmp'); # get the new working directory $cwd = `pwd`; print "New directory: $cwd\n";
In the above example, we first use backticks to execute the pwd
command and get the current working directory. We then print this directory to the screen.
We then use the chdir
function to change the working directory to /tmp
. We use backticks again to execute the pwd
command and get the new working directory, which we print to the screen.
When run, the above example will output something like the following:
Current directory: /home/user New directory: /tmp
This indicates that the working directory was successfully changed from /home/user
to /tmp
.
Note that the chdir
function can also be used with a block, which temporarily changes the working directory only for the duration of the block. For example:
use strict; use warnings; { # change the working directory temporarily local $ENV{PWD} = '/tmp'; chdir; # current working directory is now /tmp my $cwd = `pwd`; print "Temporary directory: $cwd\n"; } # current working directory is back to its original value my $cwd = `pwd`; print "Current directory: $cwd\n";
In this example, we use the local
keyword to create a local copy of the PWD
environment variable and set it to /tmp
. We then call the chdir
function without any arguments, which changes the working directory to /tmp
. We use backticks again to execute the pwd
command and get the new working directory, which we print to the screen.
After the block, the working directory is changed back to its original value, which we again print to the screen.