3 perlpragma - how to write a user pragma
7 A pragma is a module which influences some aspect of the compile time or run
8 time behaviour of Perl, such as C<strict> or C<warnings>. With Perl 5.10 you
9 are no longer limited to the built in pragmata; you can now create user
10 pragmata that modify the behaviour of user functions within a lexical scope.
12 =head1 A basic example
14 For example, say you need to create a class implementing overloaded
15 mathematical operators, and would like to provide your own pragma that
16 functions much like C<use integer;> You'd like this code
20 my $l = MyMaths->new(1.2);
21 my $r = MyMaths->new(3.4);
23 print "A: ", $l + $r, "\n";
26 print "B: ", $l + $r, "\n";
30 print "C: ", $l + $r, "\n";
33 print "D: ", $l + $r, "\n";
36 print "E: ", $l + $r, "\n";
46 I<i.e.>, where C<use myint;> is in effect, addition operations are forced
47 to integer, whereas by default they are not, with the default behaviour being
48 restored via C<no myint;>
50 The minimal implementation of the package C<MyMaths> would be something like
57 use overload '+' => sub {
59 # Pass 1 to check up one call level from here
60 if (myint::in_effect(1)) {
68 my ($class, $value) = @_;
69 bless \$value, $class;
74 Note how we load the user pragma C<myint> with C<()> to prevent its C<import>
77 The interaction with the Perl compile happens inside package C<myint>:
93 my $level = shift // 0;
94 my $hinthash = (caller($level))[10];
95 return $hinthash->{myint};
100 As pragmata are implemented as modules, like any other module, C<use myint;>
115 Hence the C<import> and C<unimport> routines are called at B<compile time>
118 User pragmata store their state by writing to C<%^H>, hence these two
119 routines manipulate C<%^H>. The state information in C<%^H> stored in the
120 optree, and can be retrieved at runtime with C<caller>, at index 10 of the
121 list of returned results. In the example pragma, retrieval is encapsulated
122 into the routine C<in_effect()>. This uses C<caller(1)> to determine the
123 state of C<$^H{myint}> when each line of the user's script was called, and
124 therefore provide the correct semantics in the subroutine implementing the
127 =head1 Implementation details
129 The optree is shared between threads, which means there is a possibility that
130 the optree will outlive the particular thread (and therefore interpreter
131 instance) that created it, so true Perl scalars cannot be stored in the
132 optree. Instead a compact form is used, which can only store values that are
133 integers (signed and unsigned), strings or C<undef> - references and
134 floating point values are stringified. If you need to store multiple values
135 or complex structures, you should serialise them, for example with C<pack>.
136 The deletion of a hash key from C<%^H> is recorded, and as ever can be
137 distinguished from the existence of a key with value C<undef> with