Most Perl 5 extensions are modules which provide new functions or define classes (moose). Some modules instead influence the behavior of the language itself, such as strict
or warnings
. Such a module is a pragma. By convention, pragmas have lower-case names to differentiate them from other modules.
Pragmas work by exporting specific behavior or information into the lexical scopes of their callers. Just as declaring a lexical variable makes a symbol name available within a scope, using a pragma makes its behavior effective within that scope:
Just as lexical declarations affect inner scopes, pragmas maintain their effects within inner scopes:
use
a pragma as you would any other module. Pragmas take arguments, such as a minimum version number to use and a list of arguments to change the pragma's behavior:
Sometimes you need to disable all or part of those effects within a further nested lexical scope. The no
builtin performs an unimport (importing), which undoes the effects of well-behaved pragmas. For example, to disable the protection of strict
when you need to do something symbolic:
Perl 5.10.0 added the ability to write your own lexical pragmas in pure Perl code. perldoc perlpragma
explains how to do so, while the explanation of $^H
in perldoc perlvar
explains how the feature works.
Even before 5.10, Perl 5 included several useful core pragmas.
the
strict
pragma enables compiler checking of symbolic references, bareword use, and variable declaration.the
warnings
pragma enables optional warnings for deprecated, unintended, and awkward behaviors.the
utf8
pragma forces the parser to interpret the source code with UTF-8 encoding.the
autodie
pragma enables automatic error checking of system calls and builtins.the
constant
pragma allows you to create compile-time constant values (see the CPAN'sConst::Fast
for an alternative).the
vars
pragma allows you to declare package global variables, such as$VERSION
or@ISA
(blessed_references).the
feature
pragma allows you to enable and disable post-5.10 features of Perl 5 individually. Whereuse 5.14;
enables all of the Perl 5.14 features and thestrict
pragma,use feature ':5.14';
does the same. This pragma is more useful to disable individual features in a lexical scope.the
less
pragma demonstrates how to write a pragma.
The CPAN has begun to gather non-core pragmas:
autobox
enables object-like behavior for Perl 5's core types (scalars, references, arrays, and hashes).perl5i
combines and enables many experimental language extensions into a coherent whole.autovivification
disables autovivification (autovivification)indirect
prevents the use of indirect invocation (indirect_objects)
These tools are not widely used yet. The latter two can help you write more correct code, while the former two are worth experimenting with in small projects. They represent what Perl 5 might be.
Hey! The above document had some coding errors, which are explained below:
- Around line 3:
-
A non-empty Z<>