Perl

  1. Home
  2. Computing & Technology
  3. Perl

Globbing a Directory

How to read a directory in Perl

From About.com

It's very simple to print a list of all files in a directory using the built-in Perl glob function. Let's look over a short script that globs and prints a list of all files, in the directory containing the script itself:
#!/usr/bin/perl -w

@files = <*>;
foreach $file (@files) {
  print $file . "\n";
}
When you run the program, you'll see it output the filenames of all files in the directory, one per line. The glob is happening on the first line, as the <*> characters pulls the filenames into the @files array.
@files = <*>;
Then we simply use a foreach loop to print out the files in the array.

You can include any path in your filesystem between the <> marks. For example, say your web site is in the /var/www/htdocs/ directory and you want a list of all the files:

@files = </var/www/htdocs/*>;
Or if you just want a list of the files with the extension .html:
@files = </var/www/htdocs/*.html>;
More Perl Quick Tips

Explore Perl

About.com Special Features

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. File System
  6. Perl globbing tutorial - Reading a directory in perl, learn how to get a directory list.

©2009 About.com, a part of The New York Times Company.

All rights reserved.