Skip to content

Instantly share code, notes, and snippets.

@DavidGriffith
Created June 23, 2014 09:29
Show Gist options
  • Save DavidGriffith/0b3566109a160eb88601 to your computer and use it in GitHub Desktop.
Save DavidGriffith/0b3566109a160eb88601 to your computer and use it in GitHub Desktop.
A simple way to serve up fortunes on a webpage.
#!/usr/bin/perl -w
# This script picks a fortune out of a fortune file and prints it.
# We start by counting the number of fortune separators there are in the file
# '%'. Pick a random number from zero to the number of separators found.
# Then rewind the file and count out that many separators.
# Next we load the upcoming fortune into a string, making sure not
# load the trailing separator, if there is one. Then print.
# This script is optimized for memory usage.
# It will not inhale an entire fortune file. Therefore this script is ideal
# for serving up fortunes from a very large file.
my $www_root = "/var/www/661.org";
my $file = "$www_root/fortune.txt";
my $number;
my $fortune;
my $target;
if (!open(F, $file)) {
print "Oops. Cannot open fortune file '$file'!\n";
exit;
}
srand(time);
# Count the number of fortunes (or separators).
$number = 0;
while (<F>) { if (m/^%+$/ ) { $number++; } }
RESTART:
# Pick a random index.
$target = (rand(1000) * time) % ($number + 1);
$number = 0;
# Rewind. Count separators until we get to the fortune we want.
# Then load up $fortune until the next separator or the fortune file ends.
seek F, 0, 0;
while (<F>) {
if ($number > $target) { last; }
if (m/^%$/) { $number++; }
if ($number == $target && !(m/^%+$/)) {
$fortune .= $_;
}
}
# Two separators in a row and trailing separators will yield a null fortune.
# If that's what we got, try again.
if (!$fortune) { goto RESTART; }
print "Content-type: text/plain\n\n";
print $fortune;
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment