Free Perl Tutorials

Navigate Directories Using PERL

So we've covered how to handle files, now its time to manage directories or folders in PERL! The process is fairly straightforward, and will take you little if any time to learn.

For this exercise, go into your C:/Test folder and create 2 test folders, we'll call them "test1" and "test2".

So our structure is as follows: C:/Test/test1 and C:/Test/test2. Now in the "test1" folder, I have place a few files so we can demonstrate how to view all files associated with a directory or folder:

HOW TO OPEN A DIRECTORY OR FOLDER USING PERL

Here is the code to open a directory and view the files in it using PERL:

#opendir opens the correct folder or directory
opendir(DIR, 'test');

#@files creates an array of all the files in the folder or
#directory while'readdir' reads the folders contents.
@myfiles = readdir(DIR);

#close the directory or folder
closedir(DIR);

#prints the files in the directory
print "@myfiles\n";


So, as you can see, the code to open a file or open a directory is very similar!

HOW TO CHANGE A DIRECTORY OR FOLDER USING PERL

This code is very similar to what is above. After you've already opened the primary directory, simply use the chdir function to navigate to a new subfolder.

Here is an example of how to use perl to change to a different subfolder:

opendir(DIR,'test');
chdir 'test1';
closedir(DIR);


We use "chdir" to change directories in PERL! Note: To navigate to the folder above your current one, you can simply place a '.' in the position of the folder you wish to navigate to!

HOW TO ADD A DIRECTORY OR FOLDER USING PERL

This is the code to add a folder to a directory:

opendir(DIR, 'test');
mkdir 'test33';
close(DIR);


We use the "mkdir" function to create a new directory in PERL!

Here is an example of the code used to remove a directory:

opendir(DIR, 'test');
rmdir 'test2';
close(DIR);



HOW TO REMOVE A DIRECTORY OR FOLDER USING PERL

Here is an example of the code used to remove a directory:

opendir(DIR, 'test');
rmdir 'test2';
close(DIR);


To delete a folder or directory using PERL, use the "rmdir" function!

Now you can move around open, create, remove or delete folders and directories in perl. To test your ability to navigate around your system using perl, you can add an array and print that array to your screen.