Saturday, March 29, 2008

Perl: Read files from given folder or directory


Share at Facebook

If you want to get all the file names from a given directory using Perl script, you can use the glob function of Perl. This Perl function will return an array of filenames from the given folder. The use of the glob function is as below.

my @files = glob("c:\\perl\\bin\\*"); ## will return all file
my @files = glob("c:\\perl\\bin\\*.exe"); ## will return all .exe file
my @files = glob("/root/temp/*"); ## An example of Linux directory

Below is a complete code that reads all the file names from the given directory, and strip the file name from the full path name.

my @files = glob("c:\\perl\\bin\\*");
foreach my $file(@files){
   print "FileName With Path[$file]\n";

   ## Strip only the file name from the full path
   if($^O =~ /mswin32/i){
      $file =~ s/.*\\//;
   }
   ## You can add more elsif, i'm giving a linux example
   else{
      $file =~ s/.*\///;
   }
   print "FileName Without Path [$file]\n";
}




No comments: