Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Perl Unicode TutorialFrequently Asked Questions abo ... (Berikutnya)
Tutorials

How to write a user pragma

Daftar Isi

NAME

perlpragma - how to write a user pragma

DESCRIPTION

A pragma is a module which influences some aspect of the compile time or runtime behaviour of Perl, such as strict or warnings. With Perl 5.10 youare no longer limited to the built in pragmata; you can now create userpragmata that modify the behaviour of user functions within a lexical scope.

A basic example

For example, say you need to create a class implementing overloadedmathematical operators, and would like to provide your own pragma thatfunctions much like use integer; You'd like this code

  1. use MyMaths;
  2. my $l = MyMaths->new(1.2);
  3. my $r = MyMaths->new(3.4);
  4. print "A: ", $l + $r, "\n";
  5. use myint;
  6. print "B: ", $l + $r, "\n";
  7. {
  8. no myint;
  9. print "C: ", $l + $r, "\n";
  10. }
  11. print "D: ", $l + $r, "\n";
  12. no myint;
  13. print "E: ", $l + $r, "\n";

to give the output

  1. A: 4.6
  2. B: 4
  3. C: 4.6
  4. D: 4
  5. E: 4.6

i.e., where use myint; is in effect, addition operations are forcedto integer, whereas by default they are not, with the default behaviour beingrestored via no myint;

The minimal implementation of the package MyMaths would be something likethis:

  1. package MyMaths;
  2. use warnings;
  3. use strict;
  4. use myint();
  5. use overload '+' => sub {
  6. my ($l, $r) = @_;
  7. # Pass 1 to check up one call level from here
  8. if (myint::in_effect(1)) {
  9. int($$l) + int($$r);
  10. } else {
  11. $$l + $$r;
  12. }
  13. };
  14. sub new {
  15. my ($class, $value) = @_;
  16. bless \$value, $class;
  17. }
  18. 1;

Note how we load the user pragma myint with an empty list () toprevent its import being called.

The interaction with the Perl compilation happens inside package myint:

  1. package myint;
  2. use strict;
  3. use warnings;
  4. sub import {
  5. $^H{"myint/in_effect"} = 1;
  6. }
  7. sub unimport {
  8. $^H{"myint/in_effect"} = 0;
  9. }
  10. sub in_effect {
  11. my $level = shift // 0;
  12. my $hinthash = (caller($level))[10];
  13. return $hinthash->{"myint/in_effect"};
  14. }
  15. 1;

As pragmata are implemented as modules, like any other module, use myint;becomes

  1. BEGIN {
  2. require myint;
  3. myint->import();
  4. }

and no myint; is

  1. BEGIN {
  2. require myint;
  3. myint->unimport();
  4. }

Hence the import and unimport routines are called at compile timefor the user's code.

User pragmata store their state by writing to the magical hash %^H,hence these two routines manipulate it. The state information in %^H isstored in the optree, and can be retrieved read-only at runtime with caller(),at index 10 of the list of returned results. In the example pragma, retrievalis encapsulated into the routine in_effect(), which takes as parameterthe number of call frames to go up to find the value of the pragma in theuser's script. This uses caller() to determine the value of$^H{"myint/in_effect"} when each line of the user's script was called, andtherefore provide the correct semantics in the subroutine implementing theoverloaded addition.

Key naming

There is only a single %^H, but arbitrarily many modules that wantto use its scoping semantics. To avoid stepping on each other's toes,they need to be sure to use different keys in the hash. It is thereforeconventional for a module to use only keys that begin with the module'sname (the name of its main package) and a "/" character. After thismodule-identifying prefix, the rest of the key is entirely up to themodule: it may include any characters whatsoever. For example, a moduleFoo::Bar should use keys such as Foo::Bar/baz and Foo::Bar/$%/_!.Modules following this convention all play nicely with each other.

The Perl core uses a handful of keys in %^H which do not follow thisconvention, because they predate it. Keys that follow the conventionwon't conflict with the core's historical keys.

Implementation details

The optree is shared between threads. This means there is a possibility thatthe optree will outlive the particular thread (and therefore the interpreterinstance) that created it, so true Perl scalars cannot be stored in theoptree. Instead a compact form is used, which can only store values that areintegers (signed and unsigned), strings or undef - references andfloating point values are stringified. If you need to store multiple valuesor complex structures, you should serialise them, for example with pack.The deletion of a hash key from %^H is recorded, and as ever can bedistinguished from the existence of a key with value undef withexists.

Don't attempt to store references to data structures as integers whichare retrieved via caller and converted back, as this will not be threadsafe.Accesses would be to the structure without locking (which is not safe forPerl's scalars), and either the structure has to leak, or it has to befreed when its creating thread terminates, which may be before the optreereferencing it is deleted, if other threads outlive it.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Perl Unicode TutorialFrequently Asked Questions abo ... (Berikutnya)