http://qs321.pair.com?node_id=415908

I'm not sure in which part of the site to post this, as it's threefold... So I'll just throw it in Meditations so we can also meditate about how to categorize the post :)

A Cool use of Perl: An example (and to proof that it can be done) of a very simple application that uses HTTP::Daemon and HTML and should thus be portable and easy to make.

The meditative part of this thread: is this a good or a bad idea? It's portable, but some platforms have native widgets that would be nicer to create a GUI in.

And finally, a small quest for Perl wisdom: what's a portable way to find out if the user has left the "site" or closed the browser window? So far, I've told users of these little applications to hit ^C when done, but that's not pretty.

#!/usr/bin/perl -w # Pizza calculator, an example of how to build a portable web based # GUI application. use strict; use HTTP::Daemon; use HTTP::Status; use CGI::Simple; sub res { HTTP::Response->new( RC_OK, OK => [ 'Content-Type' => 'text/html' ], shift ) } my %pages = ( index => sub { res qq[ <html><body> <h1>Pizza cost calculator</h1> <form method=post action=calc> Total cost: <input name=cost><br> Number of eaters: <input name=ppl><br> <input type=submit value=Submit> </form> </body></html> ]; }, calc => sub { my ($request) = @_; my $cgi = CGI::Simple->new( $request->content ); res sprintf q[ <html><body> <h1>Result</h1> Cost per eater: %.2f<br> <a href=index>Again!</a> </body></html> ], $cgi->param('cost') / $cgi->param('ppl'); }, ); my $daemon = HTTP::Daemon->new(LocalAddr => '127.0.0.1') or die; my $ppid = $$; if (my $pid = fork) { while (my $client = $daemon->accept) { while (my $request = $client->get_request) { my ($page) = $request->url->path =~ m[^/(\w+)$]; $page ||= 'index'; if (exists $pages{$page}) { $client->send_response( $pages{$page}->($request) ); } else { $client->send_error(RC_NOT_FOUND); } } $client->close; } } elsif (defined $pid) { my $url = $daemon->url; my @browsers = qw(firefox konqueror mozilla opera start); { @browsers or die "Couldn't start a browser."; my $b = shift @browsers; my $r = system("$b $url"); redo if $r; } } else { die "Couldn't fork!"; }

Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }