Category: Utility
Author/Contact Info m3@ok.ru
Description: It is everyday task to work with all files of certain type or with names matching some pattern in some directory.
I use simple sub to prepare a list of such files ready for further work.
I work with Windows, so Unix boys and girls can want to change something...
my @Dir = ReadDirectory ("dirName", "\.html");

for my $file (@Dir) {
  open (InFile, "<$file");
  #.....................
  close (InFile);
}


sub ReadDirectory {

  my $DirName = shift;
  my $FilePattern = shift;

  opendir (DIR, $DirName) or die "can not opendir $DirName: $!\n";
  my @DirListing = readdir(DIR);
  closedir (DIR) or die "can not closedir $DirName: $!\n";

  if ($DirName eq '.') {$DirName = ''}
  else {$DirName .= '\\'}

  my @Dir = ();
  for my $file (@DirListing) {
    if ($file =~ /$FilePattern/) {
      push @Dir, "$DirName$file";
    }
  }

  return @Dir;

} # (sub ReadDirectiry)
Replies are listed 'Best First'.
Re: List of selected files
by merlyn (Sage) on Oct 06, 2001 at 20:18 UTC
    A more compact pattern might be
    my @Dir = ReadDirectory("dirName", qr/\.html/); sub ReadDirectory { local *MYDIRHANDLE; my ($dir, $pat) = @_; opendir MYDIRHANDLE, $dir or return (); map "$dir/$_", grep $pat, readdir MYDIRHANDLE; }
    In fact, that's usually short enough that I just open-code it rather than have a subroutine.

    -- Randal L. Schwartz, Perl hacker

Re: List of selected files
by premchai21 (Curate) on Oct 06, 2001 at 18:35 UTC
    You might want to change backslashes to slashes, which will work on both Win and *n?x. They're also easier to use because you don't have to worry about them escaping some other character.