Besides allong you to manipulate files very easily, perl also allows you manipulate directories in a very straight forward manner. Almost like files.
Let's start with some basic things. In order to change to a particular directory you would use the chdir() function. This function takes one argument. The name of the directory to which you wish to change.
chdir("/home/abc123");
If perl was able to change directories very easily then true would be returned otherwise you get a false. Remember that true means any number, or character other that zero, null or undefined.
You can get a list of files in a directory using the * operator in conjunction with the diamond operator(<>). This is called Globbing. If I'm in the /home/abc123/ and I want a list of all the files that exist I would do the following:
@files_found = </home/abc123/*>;
or
@files_found = </home/abc123/*.pl>;
This will give you the names of all the files in the directory that match the specified pattern.
You can also open a directory using directory handles. To open a directory you would use the function opendir():
opendir(DIRHANDLE,"/home/abc123");
Now you can use the directory handle to manipulate the files using the readdir() function. This will also give you access to the filenames. If you invoke the readdir() function in a scalar context then it will return the next filename in the list, if you call it in an array context then it will return a list of all the files in the directory.
$filename = readdir(DIRHANDLE); #returns one filename
@filenames = readdir(DIRHANDLE); #returns a list of filenames
Once you are done with the directory you can close it using the closedir() function:
closedir(DIRHANDLE);
![]() |
![]() |
![]() |