Perl Part I · Module 2 · Variables, Scalars, and Data Types
Constants: use constant and Readonly
Some values in a script are decisions rather than data: a retry limit, a marker string a tool writes, an exit code that means something specific. Those deserve a name and should never change while the program runs. Perl's usual answer is use constant, and it behaves slightly oddly in three ways that puzzle people — no dollar sign, no substitution inside quotes, and a compile error if you assign to it. All three have the same cause, and once you know it the oddness disappears: use constant does not create a variable at all.
Foundation11 min readPerlPart IFundamentalsConstantsReadability
Part I · Module 2 · Chapter 2.11 · Constants: use constant and Readonly
1. Values That Are Decisions
Chapter 2.2 argued for naming values instead of repeating literals. Some of those names deserve a stronger promise than a variable gives: not merely "this value is called MAX_RETRIES" but "this value will not change while the program runs".
The candidates are usually decisions rather than measurements:
- a retry or timeout limit
- a marker string that a tool is known to emit
- an exit code with an agreed meaning
- a threshold the team settled on
A variable can hold any of these, and a variable can also be assigned to by accident three hundred lines later. A constant cannot.
2. Declaring One
use strict;
use warnings;
use constant MAX_RETRIES => 3;
print MAX_RETRIES, "\n";3Three things about that declaration are worth naming:
use constantis a pragma, likeuse strictfrom Chapter 1.10. It acts at compile time, which is why the constant exists for the whole file regardless of where the line sits — though convention puts it at the top with the otheruselines.=>separates the name from the value. It is a comma that also quotes the word on its left, and Chapter 6.2 covers it properly.MAX_RETRIEShas no sigil. All-capitals is a strong convention for constants, not a rule.
3. It Is Not a Variable
Here is the fact that explains everything else: use constant creates a subroutine — a small named piece of code that returns the value. Module 10 covers subroutines; you need only the consequence.
Because it is a subroutine and not a variable:
It has no sigil. There is no $MAX_RETRIES, because there is no scalar. The name stands alone.
It does not interpolate. Putting it inside double quotes gives you the letters:
use strict;
use warnings;
use constant MAX_RETRIES => 3;
print "MAX_RETRIES\n";MAX_RETRIESThat is not a bug. Chapter 2.5 established that double quotes substitute variables, and this is not one. Perl had nothing to substitute, so it printed the text.
Assigning to it fails at compile time:
Can't modify constant item in scalar assignment at constant.pl line 5, near "4;"
Execution of constant.pl aborted due to compilation errors.Note the class of that failure — aborted due to compilation errors, so by Chapter 1.5 nothing ran. That is the promise being kept: the mistake cannot reach production, because the file containing it is not a valid program.
Contrast a variable, which accepts the same edit silently:
use strict;
use warnings;
my $max = 3;
$max = 4;
print "$max\n";4Both lines are legal. That is the entire difference between the two tools.
4. Printing One Inside a Sentence
Since a constant does not interpolate, building a message with one means keeping it outside the quotes:
use strict;
use warnings;
use constant MAX_RETRIES => 3;
print "retry limit is ", MAX_RETRIES, "\n";retry limit is 3That is the readable form and the one to use. You will also meet this in real code:
print "retry limit is @{[ MAX_RETRIES ]}\n";It works — it prints the same line — and it relies on machinery from Module 7. Recognise it when you see it; prefer the comma form while you are learning, because a reader of your script should not need Module 7 to follow a print.
5. Readonly, and an Honest Note
The other name you will see is Readonly, a module that provides constants which do behave like variables — with sigils, and with interpolation inside quotes. That makes it read more naturally than use constant, which is why some codebases prefer it.
Two things you should know before relying on it:
- It is not part of core Perl. It comes from CPAN and has to be installed, which on a managed engineering machine is a request rather than a command — the situation Chapter 1.2 described.
- It was not available on the machine these notes were written on, so no
Readonlyexample in this chapter was executed. Rather than invent output, this chapter states what the module is for and leaves its behaviour to its own documentation, whichperldocwill show you once it is installed — Chapter 1.14 covers that.
use constant is in core Perl and is always available. For Part I that makes it the right default, and the reason to know Readonly exists is so that you recognise it in code you inherit.
6. Why This Matters in Engineering Work
A long flow script accumulates numbers whose meaning is not obvious: a 3, a 7200, a 0.95. Each one was a decision somebody made, and a literal records the decision without recording the reason or the intent that it stay fixed.
Naming it does two things that matter later. It gives the value a place where a comment explaining why can live, which Chapter 1.9 argued for. And when the number is wrong, there is exactly one line to change rather than a search for every occurrence — the point Chapter 2.2 made about literals, strengthened by the guarantee that nothing else reassigned it along the way.
The compile-time refusal is the part that earns its place in automation. A limit that a later edit silently changes is worse than a literal, because the script still looks correct at the point you are reading. A constant converts that possibility into a program that will not start.
7. Common Mistakes
Writing $MAX_RETRIES. There is no scalar of that name. Under use strict you get the undeclared-variable compile error from Chapter 1.10, which is a clear signal once you recognise it.
Expecting interpolation. "MAX_RETRIES" prints the letters. Keep the constant outside the quotes, as in §4.
Assigning to one. A compile error, and that is the feature.
Using a constant for something that is not constant. A retry limit is a decision; a retry count changes as the script runs and belongs in a variable. The test is whether the value is an input to the program's behaviour or a result of it.
Assuming Readonly is available. It is a CPAN module. Check before writing code that depends on it, as §5 describes.
8. What You Should Be Able to Say Now
- A constant names a value that must not change while the program runs.
use constant NAME => value;is the core-Perl way to declare one, and it acts at compile time.- It creates a subroutine, not a variable — which is why there is no sigil.
- It does not interpolate, because double quotes substitute variables and a constant is not one.
- Assigning to a constant is a compile error, so nothing runs.
Readonlyis a CPAN module offering interpolating constants; it is not in core and was not tested here.- Use a constant for a decision and a variable for a value the program computes.
9. Exercise
Exercise 1 — declare and print. Write a script with a constant PASS_MARK set to 50 and print the sentence pass mark is 50 using the comma form from §4. Then try it with the constant inside the quotes and record what changes.
Exercise 2 — produce the compile error. Add a line that assigns a new value to your constant. Run it, record the message, and say — using Chapter 1.5 — why the sentence from Exercise 1 did not print.
Exercise 3 — explain the three oddities. In one sentence each, explain why a constant has no sigil, does not interpolate, and cannot be assigned to. All three answers should refer to the same underlying fact.
Exercise 4 — choose the right tool. For each, say whether you would use a constant or a variable, and why in one clause: (a) the maximum number of times to retry a failed simulation; (b) the number of retries used so far; (c) the exact string a tool prints when a run completes; (d) the name of the test currently being processed.
10. Summary
- A constant names a value that must not change, which suits limits, markers, thresholds and exit codes.
use constantis core Perl and acts at compile time.- It creates a subroutine, not a variable. Every surprise follows from that: no sigil, no interpolation, no assignment.
- Assignment is a compile error, so the mistake cannot reach a run.
- Keep a constant outside quotes when building a message; the
@{[ ... ]}idiom exists but needs Module 7. Readonlyis a CPAN module, not core, and was not available to test here.- Decisions get constants; computed values get variables.
Chapter 2.12 looks at a group of variables you have met in passing throughout Module 1 — the ones whose names are punctuation.
Where this fits
Part of the Perl curriculum.
