in reply to How do I read all the file names of a directory into an array?

I would like to read the names of all the files in a directory of mine into an array so that I can convert each file name into a link to that file.

very simply, use opendir, readdir, and closedir

my $dir = '/'; ## rem trailing slash my $body; ## our file list my $saveFile = '/dev/null'; ## file to save links opendir( MYDIR, $dir ) or die 'opendir'; $body = join( "\n", ## make it legible map { '<a href="$_">$_</a><br>' } ## format each file sort { $a cmp $b } ## sort them grep { ! /^\./ } ## no .name files grep { -T "$dir$_ } ## only text files readdir MYDIR ); closedir MYDIR; ## build your link page ## using $body open( FILE, $saveFile ) or die 'open'; print FILE <<EOF; <HTML> <HEAD> <TITLE>My Files</TITLE> <BODY> $body </BODY> </HTML> EOF close FILE;

see also join, grep, map, and sort
( along with Schwartzian Transform and file test operators )

--jj--

  • Comment on Re: How do I read all the file names of a directory into an array?
  • Download Code

Replies are listed 'Best First'.
Re: Answer: How do I read all the file names of a directory into an array?
by chipmunk (Parson) on Dec 12, 2000 at 02:06 UTC
    A tip about grep and map: using two in a row is almost always unnecessary. For example, the grep {} grep {} in the above code can be made into a single grep {} with the and operator.
    map { qq{<a href="$_">$_</a><br>} } ## format each file sort ## sort them grep { !/^\./ and -T "$dir$_" } ## no .name files, text fil +es only readdir MYDIR