1. Perl
  2. builtin functions
  3. here

chdir function - change current directory

Use the chdir function to change the current directory . The current directory of the shell or command prompt is not affected, only the current directory is changed in the Perl program.

chdir $dir;

This is an example to change the current directory. Be sure to handle the error in consideration of the case where the directory does not exist. If it fails, the content of the error is stored in $!.

my $dir = '/ etc';
chdir $dir
  or die "Cannot change working directory $dir:$!";

Example

This is an example to change the current directory.

use strict;
use warnings;

# Change the current directory.
# chdir $dir;

# Preparation (creating a directory)
my $dir = "dir_20080528_ $$";
mkdir $dir
  or die "Unable to create $dir.:$!";
print "Preparation: $dir has been created.\n\n";

print "1: Change the current directory.\n";
chdir $dir
  or die "Unable to change current directory to $dir .:$!";

print "The current directory has changed to $dir.";

Related Informatrion