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

hello all, i have a script that will have an @array that could be defined near the top of the script within my list of global declarations.
is it possible to open a dir and read it into an array in one fell swoop?
currently, i am using:

opendir(DIR,"$dir"); @array = readdir(DIR);

humbly -c

Replies are listed 'Best First'.
(ar0n: glob) Re: opendir, readir into @array in one line?
by ar0n (Priest) on Jul 23, 2001 at 19:29 UTC
Re: opendir, readir into @array in one line?
by MZSanford (Curate) on Jul 23, 2001 at 19:31 UTC
    without using backticks, you could try :
    # bad @array = `ls $dir`; # better @array = glob("$dir/*"); # i usually use what you already had opendir(DIR,"$dir"); @array = readdir(DIR); closedir(DIR);

    remeber the immortal word's of Socrates who said, "I drank what ?"
Re: opendir, readir into @array in one line?
by nardo (Friar) on Jul 23, 2001 at 20:12 UTC
    @array = readdir(DIR) if(opendir(DIR, $dir));
Re: opendir, readir into @array in one line?
by abstracts (Hermit) on Jul 23, 2001 at 22:32 UTC
    Hello

    You wondered about whether you can do @array = readdir(DIR)

    I wonder why you wonder :-). You could've just consulted the perldocs for the answer since it clearly states that:

          readdir DIRHANDLE
                   Returns the next directory entry for a directory
                   opened by "opendir".  If used in list context,
                   returns all the rest of the entries in the direc-
                   tory.  If there are no more entries, returns an
                   undefined value in scalar context or a null list
                   in list context.
    
    Does this help?

    Aziz,,,

Re: opendir, readir into @array in one line?
by mugwumpjism (Hermit) on Jul 23, 2001 at 19:38 UTC
    sub files_in_dir { my ($dir) = (@_); ( -d $dir ) or die "No such directory $d"; opendir DIR, $d or die "Opendir failed; $!"; my @files = grep !/^\.\.?$/, DIR; closedir DIR; return @files; }

    Meanwhile, in a nearby piece of code...

    my @files = files_in_dir "/my/dir";

    Close to what you wanted?

    srand 3.14159; print join("", sort{rand 1<0.5}map{$_^"\037"}split m{ }x,"qmptk|z~wOzm??l]pUqx^k?j"),",\n";
Re: opendir, readir into @array in one line?
by Wookie (Beadle) on Jul 24, 2001 at 14:38 UTC
    In terms of efficency - I'm not too up to speed on perl internals etc. - but isn't it likely that glob constructs lead back to the same underlying functions?

    That is - opendir and readdir (c functions - not perl) ? So ultimately - aren't most of these options going to be as efficent (or close to it)?
    game(Wookie,opponent) eq 'Wookie' ? undef $problem : remove_limbs(arms,opponent);