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:
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 #this doesn't do what you want
say (CURRENT_TIME) # 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.
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
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.