Last Updated: September 16, 2020
· worr

Constants in Perl

Today I'm going to talk about a fairly simple topic that came up in a Perl presentation I gave on Computer Science House @ RIT.


Constants are a pretty old feature in Perl and also a pretty useful feature. The builtin constant pragma in Perl allows you to create constants at compile time. It's used like this

use constant NAME => 'William Orr';

This creates a constant called NAME, that can be used like this:

say NAME;

What the hell is a constant?

Constants, as you might notice, don't have any kind of preceding sigil. This is because, constants are actually implemented as functions that return the predeclared value.

This explains some things, such as constants can only be scalars or lists, not arrays or hashes.

It's also worth noting that the constant pragma imposes list context on its arguments. Something like

use constant CURRENT_TIME => localtime();

will probably not do what you want (that is give you a string of the current time).

Not only that, if you try and use the above constant, you might run into errors trying to index into it.

say CURRENT_TIME[0] #this doesn't do what you want
say (CURRENT_TIME)[0] # this, however, does

This is because CURRENT_TIME is a list, not an array.

But Will, I want interpolation!

Cool, I do too. Let's talk about interpolation.

use Const::Fast;
const my $NAME => 'William Orr';
say "My name is $NAME";

Const::Fast is a fantastic module that gives you the ability to quickly create constants without the problems that use constant and the stdlib Readonly introduce.


Constants are useful, and Const::Fast is the best and easiest way to make and use constants. Failing that, the builtin constant pragma works brilliantly.

3 Responses
Add your response

# interpolation...
use constant NAME => "Toby Inkster";
say "My name is ${\ NAME }";
over 1 year ago ·

Thanks for the response. TIL taking a reference of a literal or a return value.

Const::Fast still provides faster access by removing the function call every time you access your constant.

over 1 year ago ·

Constants created with the constant pragma don't result in function calls. They're optimized away by the compiler. (This includes constants interpolated in strings like ${\FOO}.) The only ways to force Perl not to optimize a constant away are to call it with a leading ampersand, or to call it as a method.

over 1 year ago ·