tobold.org

correct • elegant • free

△ comp.lang.perl △

◅ File opening problem.

Why does tr/A-Z/a-z/ work? ▻

doing efficient "ls" from within perl script

In article <4iafih$r2o@news.tamu.edu>,
Prasad Devi Suravarapu <suravara@eesun1.tamu.edu> wrote:
>   open(LIST, "ls |");

The canonical (also most portable, and most efficient) way to read
a directory in Perl is to use opendir, readdir, and closedir.

    opendir DIR, $dir or die "$0: can't opendir $dir: $!\n";
    @files = grep ! /^\.\.?$/, readdir DIR;
    closedir DIR;

The grep removes the `.' and `..' entries; note that your `ls'
solution will not show you any filenames beginning with `.' (unless
run as root).

The array returned by readdir is not sorted (at least under Unix),
which is the main reason for hoping that it will be significantly
faster than `ls' for an enormous directory (but readdir will be a
little bit faster even in a tiny directory).

readdir can also be used in a scalar context, in which case it returns
entries from the directory one at a time (again, unsorted).

    opendir DIR, $dir or die "$0: can't opendir $dir: $!\n";
    while ($file = readdir DIR) {
        warn "$file is setuid\n" if -u "$dir/$file";
    }
    closedir DIR;

Tim.
--
Tim Goodwin   | "Those who will not study history are
Cambridge, UK | doomed to debug it." -- Barry Shein

Original headers:

From: tim@pipex.net (Tim Goodwin)
Newsgroups: comp.lang.perl.misc
Subject: Re: doing efficient "ls" from within perl script
Date: 18 Mar 1996 17:37:23 GMT
Organization: Unipalm PIPEX
Message-ID: <4ik70j$426@wave.news.pipex.net>
References: <4iafih$r2o@news.tamu.edu>

△ comp.lang.perl △

◅ File opening problem.

Why does tr/A-Z/a-z/ work? ▻