newatperl has asked for the wisdom of the Perl Monks concerning the following question:

I trying to open all of the files in a given directory, extract a few lines, and then close them. However, I do not know the names of the files in this directory. How do I open a file without explicitly knowing its name?

Replies are listed 'Best First'.
Re: opening all files in a directory
by arturo (Vicar) on May 14, 2001 at 01:36 UTC

    Get a list of the names of the files in the directory with opendir and readdir (or use glob), and then put the filename in a variable. Skeleton code:

    my $directory = "/path/to/files"; opendir DIR, $directory or die "can't open $directory: $!\n"; while (my $file = readdir DIR) { next unless -f "$directory/$file"; open FILE, "$directory/$file" or warn "Can't open $file: $!\n", ne +xt; # do stuff to FILE close FILE; } closedir DIR;
    perl -e 'print "How sweet does a rose smell? "; chomp $n = <STDIN>; $r +ose = "smells sweet to degree $n"; *other_name = *rose; print "$other +_name\n"'
Re: opening all files in a directory
by Beatnik (Parson) on May 14, 2001 at 01:31 UTC
    Use a plain readdir...
    opendir(DIR,"."); @Files = readdir(DIR); closedir(DIR);
    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.
      appendum... You might want to do this
      @Files = grep /\w/, readdir(DIR);
      to avoid reading . and .. into the array.

      cLive ;-)

      Update:d'oh - thanks Randal.

      Appendum to appendum... "assuming your file names containword chars".

        But that'll miss the perfectly legitimate file named "!!!". Why are you ruling all of those out?

        The most straightforward is:

        @files = grep { $_ ne "." and $_ ne ".." } readdir DIR;

        -- Randal L. Schwartz, Perl hacker