A small script that selects a random file in a directory
#!/usr/local/bin/perl
print "HTTP/1.0 200 OK\n";
print "Content-type: image/gif\n\n";
opendir (HOMEDIR ,"/user/www/data/temp") ||
die (" Impossibile aprire la directory ");
@files = readdir(HOMEDIR);
closedir(HOMEDIR);
$total = 0;
foreach $file (sort @files) {
if(substr($file,0,4) eq "temp" && substr($file,14,3) eq "gif"){
@filename[$total] = $file; $total=$total + 1;}
}
srand;
$num = int(rand($total));
# print $filename;
open (GIF,"/user/www/data/temp/".@filename[$num]);
print while <GIF>;
Use of associative arrays
One of the most powerful features of Perl are associative arrays. In this
small CGI script I use this feature to produce a list of the most popular
pages on my server.
#!/usr/local/bin/perl
print "HTTP/1.0 200 OK\n";
print "Content-type: text/html\n\n";
$guestbook = "/user/gruppo_1/zito/zito/WWW/java/greetings.log";
open (IN, $guestbook) || die "Can't open $guestbook";
print "<HTML><HEAD>";
print "<TITLE>Most popular documents</TITLE>";
print "</HEAD><BODY bgcolor=white>\n";
print "<center><H2>Most popular documents</H2></center><table border=5>\n";
@content = ;
close (IN);
@content = reverse (@content);
$numvis = @content;
$count = 0;
while($count < $numvis) {
$entry = @content[$count];
$line = substr($entry,0,index($entry,"http"));
if (index($entry,"http") >= 0){
if (index($entry,"pcba10") > 20 || index($entry,"pcba10") <0 ) {
$url = substr($entry,index($entry,"http"));
$url = substr($url,0,index($url,"\n"));
$stat{$url} += 1 ;
}
}
$count++;
}
$count = 0;
foreach $url(keys(%stat)) {
$pline[$count]= "<tr><td> $stat{$url}\n <td><a href=$url>$url</a>\n";
$count++;
}
@pline = sort numer (@pline);
$numlin = @pline;
$count = 0;
while($count < $numlin) {
print "$pline[$count] \n";
$count++;
}
print "</table></BODY></HTML>\n";
sub numer {
local ($numa, $numb);
$numa = substr($a,8,index($a,"\n"));
$numb = substr($b,8,index($b,"\n"));
$retval = $numb <=> $numa;
}
end
Note that the simple instruction %stat{$url} += 1 is enough
to set up a counter for each url and increment it.
The statement: foreach $url keys(%stat)) is used afterwards to scan
the associative array. I could at this point have printed the url but
they are not ordered. For this reason I put them in a normal array @pline and
I order them with sort numer(@pline). The subroutine numer is needed since
we want to order using the numeric values for the counter instead of its
characters.