Opendir example

Shows how to load and display the contents of an directory

# load all files of the "data/" folder
# into the @files array
opendir(DIR, "data/");
@files = readdir(DIR);
# build a unsorted list from the 
# @files array:
print "<ul>";
foreach $file (@files) {
    next if ($file eq "." or $file eq "..");
    print "<li><a href=\"$file\">$file</a></li>";
print "</ul>";
Snippet Details

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!

Older comments:

Matthew Lenz January 26, 2011 at 16:42
You're both wrong. you need:

@files = grep {!/^..?/} readdir(DIR);

what you have will NOT match ANY file.
Sam November 09, 2009 at 15:28
Actually, it's:

@files = grep {!/^..?/} readdir(DIR);
on a Linux server (system) ;-)
Zho September 16, 2009 at 18:20
Thank you *SO* much.
Mats Fredriksson November 19, 2008 at 19:33
You can filter out . and .. directly in the readdir line:

@files = grep { !/^..?/ } readdir(DIR);

Saves one line of code :)