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

Alright, I'm relatively new to perl, and I think this is a pretty simple question, but for some reason my code outputs nothing. I just want to open a directory, read the filenames of all the files in it, and output that array to a file. When I run the code I just get a .txt file with nothing it in. opendir(DIR, "C:\AATv2"); my @files = readdir(DIR); closedir(DIR); open(OUT, ">environments.txt"); foreach $f (@files){ print OUT "$f\n"; } close(out); Thanks in advance. I'm also unsure why I can't put any newlines in my code. Sorry I'm a n00b at this website too.
  • Comment on reading contents of directory and printing to file.

Replies are listed 'Best First'.
Re: reading contents of directory and printing to file.
by kennethk (Abbot) on Mar 06, 2009 at 15:47 UTC

    First, please read Writeup Formatting Tips - in particular surround your code w/ <code> tags.

    An issue with your code is you have a failed opendir that never gets checked. Specifically, double quotes get interpolated, so Perl interprets the sequence \A as an escape character. This can be fixed by either escaping the slash ("C:\\AATv2") or swapping to single quotes that do not interpolate ('C:\AATv2'). See details in Quote and Quote-like Operators. In this case, this issue would have gotten caught if you had use strict;use warnings at the head of your script.

    As a second note, whenever you perform an open operation, it's a good idea to test if the open was successful, to avoid this sort of problem. This is usually done by appending or die "Open unsuccessful: $!" or some equivalent to the end of your open statement. $! contains error messages from failed library calls. You should also use a three argument open in place of the two-argument form for security reasons (open(OUT, ">", "environments.txt")).

    Finally, Perl is case sensitive, so your file handles out and OUT do not correspond.

    Following all of this advice, your code might look like this:

    use strict; use warnings; opendir(DIR, 'C:\AATv2') or die "opendir unsuccessful: $!"; my @files = readdir(DIR); closedir(DIR); open(OUT, ">", "environments.txt") or die "open unsuccessful: $!"; foreach my $f (@files) { print OUT "$f\n"; } close(OUT);