Interpolatable HTTP status codes: Another way

Robert Rothenberg recently announced HTTP::Status::Constants.:

a simple wrapper around HTTP::Status that provides read-only scalar constants for the HTTP_* constants.

Here is another way of doing that using my favorite constant creation module Const::Fast (ever since Neil Bowers’ review). The prerequisites require not much more than Perl 5.8, and it puts only one variable in package scope, rather than many.

If needed, you could easily inline this where it might be needed, rather than creating a module.

package My::HTTP::Status;

use strict;

use Exporter qw( import );
use Const::Fast;

BEGIN {
    require HTTP::Status;
    const our %HTTP => map {
        my $x = $_;
        $x =~ s/^HTTP_//;
        ($x, HTTP::Status->$_)
    } grep /^HTTP_/, @HTTP::Status::EXPORT_OK;
}

our @EXPORT = ();
our @EXPORT_OK = qw(%HTTP);

__PACKAGE__;
__END__

Now, you can use this:

$ perl -MMy::HTTP::Status=%HTTP -le 'print $HTTP{I_AM_A_TEAPOT}'
418

Note that the standard caution against exporting variables does not apply here because %HTTP is a constant hash:

$ perl -MMy::HTTP::Status=%HTTP -le '$HTTP{I_AM_A_TEAPOT} = 505'
Modification of a read-only value attempted at -e line 1.