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

Hello all, I'm trying to get a long directory listing in UNIX from within a perl script. I've attempted to use stat and readdir. Readdir only gives me the filename and stat gives me a bunch of stuff I don't want. Basically I want the equivalent of UNIX's ls -l. Is this possible with Perl functions or must I resort to the dreaded system command? TIA ...Kevin

Replies are listed 'Best First'.
Re: long directory listing in UNIX
by japhy (Canon) on Aug 28, 2001 at 23:20 UTC
    Here is what ls -l returns for one of my files:
    -rw-r--r-- 1 jeffp dialup 1233 Jul 30 18:30 resume.txt
    Breaking that into pieces, we have:
    1. file type and permissions
    2. number of links to file
    3. owner of file
    4. group of owner of file
    5. size in bytes
    6. last modified date
    7. name of file
    All these -- except for the filename, which you already have -- can be extracted from stat():
    use POSIX 'strftime'; my ($perm, $links, $uid, $gid, $size, $lmod) = (stat $file)[2,3,4,5,7,9] my $user = getpwuid($uid); my $group = getgrgid($gid); my $date = strftime("%b %e %R", localtime($lmod));
    You actually need to modify that a tiny bit, in case the file was modified more than a year ago; but that's an academic exercise.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Thanks for the help. I didn't realize it would be so easy to use getpwuid, getgrgid, and strftime to get the format I wanted. I never really used these before. The only other issue I had was the permissions format which I easily re-formatted with the nifty Stat::lsMode module. No system command needed! Many many thanks! ...Kevin
        Ooops, I meant to include the Stat::lsMode module demonstration, but forgot. I'm glad you found it on your own.

        _____________________________________________________
        Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: long directory listing in UNIX
by count0 (Friar) on Aug 28, 2001 at 23:05 UTC
    There may be modules to get the info, but I'm not sure. You should probably check search.cpan.org.

    Using readdir() and stat() are probably the best ways to do it. If you don't want all of the info returned by stat, then take a slice of it.
    For example, if you only want the access and modify times of a file, do something like:
    my ($atime_stamp, $mtime_stamp) = (stat $file)[8,9];