Tux

...making Linux just a little more fun!

2-cent Tip: Perl Search Directory Function

Thomas Bonham [thomasbonham at bonhamlinux.org]


Tue, 27 May 2008 15:41:01 -0700

Hi All,

Here is a 2-cent tip that is a little Perl script for looping through directories.

#!/usr/bin/perl
# Thomas Bonham
# Create on 05/27/2008
# Function is to list all contents of a directory
 
use Cwd;
 
sub searchdir
{
  my $dir = shift;
  my $cwd = getcwd();
  if ($dir ne "") {
    unless (chdir($dir)) {
      print STDERR "Unable to chdir to $cwd/$dir: $!\n";
      return;
    }
  }
  opendir(DIR, ".");
  my @files = readdir(DIR);
  closedir(DIR);
  foreach my $file (@files) {
    next if $file eq "." || $file eq "..";
    if (-d $file) {
      searchdir($file);
      next;
    }
    # Do what you would like here
    print getcwd(),"/",$file,"\n";
  }
  chdir($cwd);
}
sub main() {
    searchdir();
}
 
main();

Thomas


Top    Back


Ben Okopnik [ben at linuxgazette.net]


Tue, 27 May 2008 20:31:13 -0400

On Tue, May 27, 2008 at 03:41:01PM -0700, Thomas Bonham wrote:

> Hi All,
> 
> Here is a 2-cent tip that is a little Perl script for looping through 
> directories.

Why not just use 'File::Find'? It's included in the default Perl install, and is both powerful and flexible.

use File::Find;
 
find(sub { do_whatever_you_want_here }, @directories_to_search);

For more info, see 'perldoc File::Find'.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Top    Back