Scratching an itch - interpolable HTTP Status constants
When working on larger web applications, I prefer to use HTTP::Status to provide human-readable constant names in the code. This is especially helpful for anything other than the common 200, 404 or 500 status codes.
But the constants exported by HTTP::Status are basically subs:
if ($response->code == HTTP_OK) { ... }
this is fine for most cases, but not when you want interpolable variables, for example, in hash keys.
So I wrote HTTP::Status::Constants. It's a simple wrapper around HTTP::Status that provides read-only scalar constants for the HTTP_*
constants.
What is the problem with hash keys?
my %hash = (
HTTP_OK() => 'OK',
);
@bor Yes, there's a simplified way of defining HTTP constants that way discussed in http://blog.nu42.com/2014/11/interpolable-http-status-code-another.html.
But there's no compile-time checking of typos. If you type $HTTP{BSD_REQUEST}, you won't get an error and may miss a subtle bug. (Note that "BSD" is one character away from "BAD", and because the letters "BSD" actually mean something, it might get missed in code review.)
If the constant is defined using Const::Fast, then you should get an error when the code is run: "Attempt to access disallowed key '...' in a restricted hash".
A minor nitpick, but stylistically, $HTTP_OK is easier to read than $HTTP{OK}.
Actually, scratch that last reply. I misread it.
Yes, you can use %hash = ( HTTP_OK() => ... ) or ${\ HTTP_I_AM_A_TEAPOT } but the code is a bit ugly.
Admittedly, this module does add extra dependencies (although some like Package::Stash are used elsewhere, e.g. Moose).