#!/usr/local/bin/perl

print "Content-type: text/plain\n\n";


sub main(){
   my $name;
   my $value;
   my $nameVals = readData() or print "foobar" and return; # Perl statements are cool
   while (($name, $value) = each %{$nameVals} ){ # Dereferencing a hash
      if ($name eq "print") {printDirData($value);} 
      elsif ($name eq "name") {printGreeting($value);} # Repeat to parse your data
   }
}# END main()


sub readData(){ # Generic CGI routine that can be copied and pasted with zero changes.
   my $i;
   my $buffer;
   my @data;
   my @names;
   my @values;
   my %nameVals;
   ($buffer = $ENV{'QUERY_STRING'}) or read (STDIN, $buffer, $ENV {"CONTENT_LENGTH"}) or return 0 ;
   @data = split (/&/, $buffer);
   for ($i = 0; $data[$i]; $i++){
      ($names[$i], $values[$i]) = split (/=/, $data[$i]);
       $names[$i] =~ tr/+/ /;
       $names[$i] =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg; #translate hex data
       $values[$i] =~ tr/+/ /;
       $values[$i] =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
       $nameVals{$names[$i]} = $values[$i]; #building the hash
   }
   return \%nameVals; # pass the hash as a reference
}# END readData()


sub printDirData(){
   my @list;

   opendir MY_DIR, "." or print "Could not open directory" and exit;
   @list = readdir (MY_DIR) or print "Could not read directory" and exit;
   close (MY_DIR);

   @list = grep(!/\.$/, @list); 

   for ($_[0]){ #implicit matching used like switch
      /all/   and last;
      /files/ and @list = grep(-f, @list), last;
      /dirs/  and @list = grep(-d, @list), last;
   }
   @list = sort @list;
   for (@list){print "$_\n";}

}# END printDirectory()


sub printGreeting(){
   print "Hello, $_[0]. Here's that list.\n\n"; # Implicit arguments passed as an array
}# END printGreeting()


main(); # C-type function call.

#end ajax.cgi
