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!";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|