|
Random quote CGI
|
Social links
Class::Prototype
WWW::Spyder Javascript tricks serial() join function Smart quotes Text to Excel Developing Featherweight Web Services with JavaScript
Miscellaneous
|
|
| Random quote CGI
|
Description There is a famous Perl one-liner for selecting a (mostly) random line from a file. This CGI is a simple application of it which also relies on the virtual file of the __DATA__ (or the __END__) section of the CGI itself. This keeps it all in a simple unit and saves you from having to read an external file or data source. While fairly simplistic, this approach is efficient and if you are manually managing a set of quotes (ie, not doing 10,000 of them from a DB or something), this is a good way to go. Sample quote (reload to pick again)
A fifth of all quotes
is this quote.
Code #!/usr/bin/perl print "Content-Type: text/html; charset=ISO-8859-1\n\n"; $/ = "\n\n"; rand($.) < 1 && ($line = $_) while <DATA>; print $line; __DATA__ Quote #1. Including <i>some HTML</i>. The second quote in a series. Three quotes are better than none. A fifth of all quotes is this quote. I want the letter M stricken from the alphabet. Description
Once it’s set up, it’s possible (if the server has SSIs on) to call it
like so in the HTML of any given page: If you’re running IIS or something else that doesn’t do server side includes or won’t do ones that execute code you could turn instead to iframes. (Thanks to Peenie Wallie for reminding me about this.) They aren’t directly supported in the XHTML 1.1 specification but they are so useful to advertisers and webservices that they seem unlikely to go away. Random quote from iframe <iframe style="border-width:0;margin:0;padding:0;" scrolling="no" src="/relative-or-full-uri/to-your-script/quote.pl" width="100%" height="100"></iframe> Layout becomes somewhat more difficult with iframes. They act like mini-pages so you have to pick fixed (or % based) heights and widths and hope your content will match up correctly. It’s possible to use JavaScript to resize it once it has content but it’s a bit complex and I’m not covering it here. The only trick in the code, besides the one-liner, is setting your record separator to 2 newlines “\n\n” so that you can have multi-line quotes. It also means you have to ensure the blank lines don’t have any spaces in them, like “\n \n.” That would slurp up the two quotes around it. Also note, different systems might use a “\r\n” for the newline and not just a “\n,” so you’d need “\r\n\r\n” or “\r?\n\r?\n” which works if they are there or not but isn’t the best if you know what line endings you’ve got on the system/computer hosting the webserver. |
|
|
Perl Books ·
CPAN ·
mod_perl ·
Perl Monks ·
Perl Mongers ·
Perl Journal ·
Use Perl ·
Perl Jobs ·
ActiveState ·
perldoc.perl.org ·
O’Reilly Perl ·
W3Schools tutorials ·
Ovid's CGI Course ·
Catalyst ·
Perl at Wikipedia
Text, original code, fonts, and graphics ©1990-2009 Ashley Pond V. |
||