Difference between revisions of "Perl"
From dbawiki
(→=A one-line web server!) |
|||
| Line 1: | Line 1: | ||
* [[http://www.socher.org/index.php/Main/PerlScriptsAndOneLiners Some one liners]] | * [[http://www.socher.org/index.php/Main/PerlScriptsAndOneLiners Some one liners]] | ||
| − | + | ===A one-line web server!=== | |
<pre> | <pre> | ||
perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' | perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' | ||
| Line 9: | Line 9: | ||
* Our callback is scanning the line in $_ for an HTTP GET request. If one is found it parses the file name into $1. Then we use $1 to create an new IO::All file object... with a twist. If the file is executable("-x"), then we create a piped command as our IO::All object. This somewhat approximates CGI support. | * Our callback is scanning the line in $_ for an HTTP GET request. If one is found it parses the file name into $1. Then we use $1 to create an new IO::All file object... with a twist. If the file is executable("-x"), then we create a piped command as our IO::All object. This somewhat approximates CGI support. | ||
* Whatever the resulting object is, we direct the contents back at our socket which is in $_[0]. | * Whatever the resulting object is, we direct the contents back at our socket which is in $_[0]. | ||
| + | |||
| + | From: [[http://www.commandlinefu.com/commands/view/5235/perl-simple-webserver commandlinefu.com]] | ||
Revision as of 22:47, 2 June 2013
A one-line web server!
perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })'
- First we accept a socket and fork the server. Then we overload the new socket as a code ref. This code ref takes one argument, another code ref, which is used as a callback.
- The callback is called once for every line read on the socket. The line is put into $_ and the socket itself is passed in to the callback.
- Our callback is scanning the line in $_ for an HTTP GET request. If one is found it parses the file name into $1. Then we use $1 to create an new IO::All file object... with a twist. If the file is executable("-x"), then we create a piped command as our IO::All object. This somewhat approximates CGI support.
- Whatever the resulting object is, we direct the contents back at our socket which is in $_[0].
From: [commandlinefu.com]