Free Perl Tutorials

PERL glob Function

The PERL glob function is another useful directory tool for pulling in file information. The thing that makes glob so useful is that you can use it to return files of only a specific extension. Before we get started, in the folder where the program you are going to make will be stored, create a subfolder called "subfolder". Then fill it with a few different file types, like a .txt file and a .jpg file. So let's dive right into the glob code to see how it is used:

#First, we create an array to store the file information and use the
#glob function to pull in information on all files from our subfolder.
@myarray = glob('subfolder/*.');

#Then we can print our array to return all files in the subfolder
print "@array\n";


The question is, how do we get it to return specific values based on a particular file extension? Simple, look at the code in bold below:

#First, we create an array to store the file information and use the
#glob function to pull in information on all .txt files
#from our subfolder.
@myarray = glob('subfolder/*.txt');

#Then we can print our array to return all files in the subfolder
print "@array\n";


Its an easy way to only pull in files of a specific extension using PERL!