6.4 Changing the Current Directory

6.4  Changing the Current Directory

 

Perl has a function called chdir that changes the current directory. Every program running has a current working directory. By default, it is the directory in which the program is located. Therefore, when a program accesses files and directories with just their names, it assumes that they are in the current working directory. Of course, it is possible to give absolute file names such as

/home/kalita/classes/cs301/perlcode/read.pl. In Unix, an absolute file name starts with / indicating the root directory for the whole system. It is also possible to give relative path names such as ../../read.pl or files/remove/recursive.pl. In the first case, the file name takes two levels up in the file hierarchy and finds the file read.pl. In the second case, the file is located two levels below the current
working directory.

We can change the current working directory in the program using the chdir command. This may obviate giving a qualified path name as we work on files and directories in the program. The first program in this section reads a directory by first changing the current working directory.

 Program 6.5

#!/usr/bin/perl
$"= "\n";
my $path = "/home/kalita/classes/cs301/perlcode/";
chdir ($path) or die "Cannot chdir to $path: $!";
opendir (DIR, ".") or die "Cannot open $path: $!";
my @files = readdir DIR;
print "@files\n";
chdir ();

The program has a variable $path that stores the fully qualified name of a directory. The program’s current working directory to begin with is wherever it is located. It then chdirs to the directory specified in $path. chdir changes the current working directory for the program. As a result, when it opendirs the current working directory . next, it opens the directory specified by $path. The program then reads the list of files in the current directory, and prints them out. Finally, it calls chdir once again with no argument. Such a call to chdir changes the current working directory to the home directory of the user. This may not necessarily be the directory in which the program is located. In Unix, every user has a home directory which can be reached with the shortened name
~username.

After changing the current working directory inside program, it is always a good habit to bring the working directory back to where it was before. Otherwise, it can become quite confusing to locate files and directories. For the program given above, we made the assumption that it is situated in the user’s home directory.