Context in Perl
Here’s the translation of the Go code to Perl, with explanations in Markdown format suitable for Hugo:
In this example, we’ll look at setting up a simple HTTP server in Perl. HTTP servers are useful for demonstrating the usage of signal handling for controlling cancellation. While Perl doesn’t have a direct equivalent to Go’s context.Context
, we can achieve similar functionality using signal handling.
#!/usr/bin/env perl
use strict;
use warnings;
use HTTP::Server::Simple::CGI;
use Time::HiRes qw(sleep);
use POSIX qw(:signal_h);
my $server = MyWebServer->new(8090);
$server->run();
{
package MyWebServer;
use base qw(HTTP::Server::Simple::CGI);
sub handle_request {
my ($self, $cgi) = @_;
print "HTTP/1.0 200 OK\r\n";
print $cgi->header('text/plain');
print "server: hello handler started\n";
# Set up signal handling
my $keep_going = 1;
local $SIG{INT} = sub { $keep_going = 0 };
# Simulate some work
for (1..10) {
last unless $keep_going;
sleep(1);
}
if ($keep_going) {
print "hello\n";
} else {
print "server: request canceled\n";
}
print "server: hello handler ended\n";
}
}
In this Perl version:
We use the
HTTP::Server::Simple::CGI
module to create a simple HTTP server.The
handle_request
method is equivalent to thehello
function in the Go example. It handles incoming requests.We use
$SIG{INT}
to set up a signal handler for the interrupt signal (Ctrl+C). This is similar to how the Go version usesctx.Done()
to detect cancellation.The
sleep
loop simulates work being done, checking the$keep_going
flag on each iteration. This is analogous to theselect
statement in the Go version.If the work completes without interruption, we print “hello”. If interrupted, we print a cancellation message.
To run the server:
$ perl server.pl &
To simulate a client request and cancellation:
$ curl localhost:8090/hello
server: hello handler started
^C
server: request canceled
server: hello handler ended
This Perl version demonstrates how to handle cancellation in a long-running HTTP request handler, similar to the Go example but using Perl-specific constructs and idioms.