Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Populating an array with contents of a directory.

by parkprimus (Sexton)
on Apr 09, 2004 at 16:27 UTC ( #343943=perlquestion: print w/replies, xml ) Need Help??

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

Wise ones,

Does anyone know a quick and dirty way to populate an array with the name of the files of a directory. Also does anyone know how to acquire the size of the files into a variable. I dont want code but perhaps a good perl module to help with these task.
Thanks in advance.

  • Comment on Populating an array with contents of a directory.

Replies are listed 'Best First'.
Re: Populating an array with contents of a directory.
by Zaxo (Archbishop) on Apr 09, 2004 at 16:30 UTC

    glob or readdir, for example:

    my $dir = '/path/to'; my @names = glob "$dir/*";

    After Compline,
    Zaxo

Re: Populating an array with contents of a directory.
by fletcher_the_dog (Friar) on Apr 09, 2004 at 18:31 UTC
    Try 'readdir' in list context:
    opendir(DIR,"/home"); my @array = readdir(DIR);
Re: Populating an array with contents of a directory.
by Anonymous Monk on Apr 09, 2004 at 19:39 UTC
    To use Zaxo's solution and get file size you may do something like this.
    #!/usr/bin/perl use strict; use warnings; my $dir = '/path'; my @names = map {[$_, -s]} glob "$dir/*"; for (@names) { printf "%-10s%s\n", reverse @$_; }
    The -s function gives the size of the file. See perldoc perlfunc. The explanation of -s and other file test operators is given near the beginning of the docs here.

    Hope this helps.

    Chris

Re: Populating an array with contents of a directory.
by disciple (Pilgrim) on Apr 10, 2004 at 00:37 UTC
    This one only returns files, excluding directories. It doesn't pull in the size of the file, but depending on where you need it, you can get that using the -s file test operator.
    #!/usr/bin/perl use strict; use warnings; my $dir = 'c:\\temp'; opendir(DIRHANDLE, $dir) or warn "Could not open directory $dir.\n"; my @dirs = grep (!/^\.\.?$/ && -f "$dir/$_", readdir(DIRHANDLE)); foreach (@dirs) { print "$_\n"; }
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://343943]
Approved by kvale
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2022-09-26 00:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer my indexes to start at:




    Results (116 votes). Check out past polls.

    Notices?