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


in reply to learning by example; please explain what this code is doing?

This code is handling and routing CGI requests based on the path (the bit that comes after the script name in a URL). It seems well thought out and covers all possible error cases. However, it is written in a style which is alien to me, and I think most monks here would reccommend against following this style.

Let's say we call the script like this:
http://localhost/script.cgi/=
The request method is GET, and the path is "/=". You get the path by calling CGI method $q->path_info

The script will call a series of subroutines until it finds a match for the request method and path. In the eval{} block you see this series of calls. One of them is:
GET qr{^/=$} => sub { print $q->header('text/html'); print $q->h1('REST API Documentation'); print $q->p('Here is a list of what you can do:');
This could be written as:
my $regex = qr{^/=$}; my $coderef = sub { print $q->header('text/html'); # etc. }; GET( $regex, $coderef );
So it sends off the $regex and the $coderef to the GET() subroutine, which then checks if the request method is 'GET' and if the path matches the regular expression. In our case the path "/=" does match the regular expression {^/=$}, so it then calls the subroutine referenced in $coderef and then exits:
$code->(); exit;
If the regex didn't match it would go on to the next test in the series, which would try to match the path to the regex {^/=/model/book/id/([\d-]+)$}
GET qr{^/=/model/book/id/([\d-]+)$} => sub { my $id = $1; # etc.
If we were to call the script with this URL
http://localhost/script.cgi/=/model/book/id/10566
then this regex would match, the code ref will be called and $id will contain the value "10566". If it didn't match the script will continue to test all the possible GET, POST, PUT and DELETE methods in the eval block until it finds a match. If it doesn't find one it returns a 404 Not Found response.