http://www.perlmonks.org?node_id=457144


in reply to Ordered Directory Listing CGI

I've revisited this script and made some enhancements and cleaned it up so it is less obfuscated. (-:
#!/usr/bin/perl -w use strict; use CGI qw/:standard/; $|=1; my $columns = param('c') || 4; opendir(DIR, ".") || die "cannot open dir: $!"; foreach (sort readdir(DIR)) { next if /~\z/ || $_ eq "ls.cgi" || $_ eq "." || $_ eq ".."; push @{ (-d) ? $_[0] : $_[1] }, (-d) ? b(a({href=>"$_"},"[ $_ ]")) : a({href=>"$_"},"$_"); } closedir DIR; # Combine dirs and files $_[3] = [ @{$_[0]}, @{$_[1]} ]; print header, start_html('Directory Listing'), h3('Directory Listing'), b("Dir Count: ".@{$_[0]}), b(", File Count: ".@{$_[1]}), table({-border=>0,-cellpadding=>5,-cellspacing=>5}, map Tr($_), grep { length($_) > 0 } map td([ splice @{$_[3]},0,$columns ]), @{$_[3]} ), end_html; __END__

Most notably I've taken another look at Aristotle's code and replaced the cute splice with array refs which turns out to be useful in the output section. E.g. I've added a directory count and a file count.

The other noticable part is that I've removed the 0 .. (@_ / $columns) and inserted a grep to eliminate extra list elements that cause extra TR elements (the initial reason I put that in there in the first place).

And, yes, I cleaned up the exclusion logic to use eq, etc.

Enjoy!

Update: Yes, the grep is a hack, for a full treatize on this issue click here.

--
hiseldl
What time is it? It's Camel Time!

Replies are listed 'Best First'.
Re^2: Ordered Directory Listing CGI
by merlyn (Sage) on May 15, 2005 at 10:25 UTC
    (-d) ? b(a({href=>"$_"},"[ $_ ]")) : a({href=>"$_"},"$_");
    You're failing to escape the HTML for your directory and filenames. This can lead to weird things when people have filenames like <b>. Simply import escapeHTML, and add that in the appropriate places:
    (-d) ? b(a({href=>"$_"},escapeHTML("[ $_ ]"))) : a({href=>"$_"},escape +HTML($_));

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.