|
| Meetings | Mailing List | Code Cookbook | Book Reviews | Links | Quiz of the Month | #define SIGILL 6 /* blech */ Larry Wall in perl.c from the perl source code You are here: home > code cookbookRandom Quote
|
| |
This little script reads a random quote from a text file and inserts it into an HTML page. In fact, it is the same script that generates the quotes on each page of this site.
Start with a plain text file formatted so that each line contains a single quote, a delimiter (e.g. a tab) and the author.
Next we'll walk through our little script. Lines starting with '#' are comments.
#!/usr/bin/perl
# file: random.pl
#always use warnings and strict
use warnings;
use strict;
#useful for debugging, but turn off for production
use CGI::Carp qw(carpout fatalsToBrowser);
#path to your file
my $quotes = 'file.txt';
# open for reading
open(QUOTE, "$quotes")
or die "Can't open $quotes: $!\n";
#read a random line
my $line;
srand;
rand($.) < 1 && ($line = $_) while <QUOTE>;
#splits on tab...change as needed
my ($quote, $author) = split("\t", $line);
#return output
print "Content-type: text/plain\n\n";
print "$quote \n$author\n";
Lastly, you will need something like:
<!--#include virtual="/cgi-bin/random.pl"-->
in your HTML where you want the text to appear.
Make sure your script is executable and enjoy!
Here is a copy of the script. random.pl
Here is a copy of the quotes. file.txt
The use of the camel image in association with the Perl language is a trademark of O'Reilly & Associates, Inc. Used with permission.
i