Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Perl pragma to use or avoid PO ...Perl pragma to set default Per ... (Berikutnya)
Pragmas

Method Resolution Order

Daftar Isi

NAME

mro - Method Resolution Order

SYNOPSIS

  1. use mro; # enables next::method and friends globally
  2. use mro 'dfs'; # enable DFS MRO for this class (Perl default)
  3. use mro 'c3'; # enable C3 MRO for this class

DESCRIPTION

The "mro" namespace provides several utilities for dealingwith method resolution order and method caching in general.

These interfaces are only available in Perl 5.9.5 and higher.See MRO::Compat on CPAN for a mostly forwards compatibleimplementation for older Perls.

OVERVIEW

It's possible to change the MRO of a given class either by using usemro as shown in the synopsis, or by using the mro::set_mro functionbelow.

The special methods next::method, next::can, andmaybe::next::method are not available until this mro modulehas been loaded via use or require.

The C3 MRO

In addition to the traditional Perl default MRO (depth firstsearch, called DFS here), Perl now offers the C3 MRO aswell. Perl's support for C3 is based on the work done inStevan Little's module Class::C3, and most of the C3-relateddocumentation here is ripped directly from there.

What is C3?

C3 is the name of an algorithm which aims to provide a sane methodresolution order under multiple inheritance. It was first introduced inthe language Dylan (see links in the SEE ALSO section), and thenlater adopted as the preferred MRO (Method Resolution Order) for thenew-style classes in Python 2.3. Most recently it has been adopted as the"canonical" MRO for Perl 6 classes, and the default MRO for Parrot objectsas well.

How does C3 work

C3 works by always preserving local precedence ordering. This essentiallymeans that no class will appear before any of its subclasses. Take, forinstance, the classic diamond inheritance pattern:

  1. <A>
  2. / \
  3. <B> <C>
  4. \ /
  5. <D>

The standard Perl 5 MRO would be (D, B, A, C). The result being that Aappears before C, even though C is the subclass of A. The C3 MROalgorithm however, produces the following order: (D, B, C, A), which doesnot have this issue.

This example is fairly trivial; for more complex cases and a deeperexplanation, see the links in the SEE ALSO section.

Functions

mro::get_linear_isa($classname[, $type])

Returns an arrayref which is the linearized MRO of the given class.Uses whichever MRO is currently in effect for that class by default,or the given MRO (either c3 or dfs if specified as $type).

The linearized MRO of a class is an ordered array of all of theclasses one would search when resolving a method on that class,starting with the class itself.

If the requested class doesn't yet exist, this function will stillsucceed, and return [ $classname ]

Note that UNIVERSAL (and any members of UNIVERSAL's MRO) are notpart of the MRO of a class, even though all classes implicitly inheritmethods from UNIVERSAL and its parents.

mro::set_mro ($classname, $type)

Sets the MRO of the given class to the $type argument (eitherc3 or dfs).

mro::get_mro($classname)

Returns the MRO of the given class (either c3 or dfs).

mro::get_isarev($classname)

Gets the mro_isarev for this class, returned as anarrayref of class names. These are every class that "isa"the given class name, even if the isa relationship isindirect. This is used internally by the MRO code tokeep track of method/MRO cache invalidations.

As with mro::get_linear_isa above, UNIVERSAL is special.UNIVERSAL (and parents') isarev lists do not includeevery class in existence, even though all classes areeffectively descendants for method inheritance purposes.

mro::is_universal($classname)

Returns a boolean status indicating whether or notthe given classname is either UNIVERSAL itself,or one of UNIVERSAL's parents by @ISA inheritance.

Any class for which this function returns true is"universal" in the sense that all classes potentiallyinherit methods from it.

mro::invalidate_all_method_caches()

Increments PL_sub_generation, which invalidates methodcaching in all packages.

mro::method_changed_in($classname)

Invalidates the method cache of any classes dependent on thegiven class. This is not normally necessary. The onlyknown case where pure perl code can confuse the methodcache is when you manually install a new constantsubroutine by using a readonly scalar value, like theinternals of constant do. If you find another case,please report it so we can either fix it or documentthe exception here.

mro::get_pkg_gen($classname)

Returns an integer which is incremented every time areal local method in the package $classname changes,or the local @ISA of $classname is modified.

This is intended for authors of modules which do lotsof class introspection, as it allows them to very quicklycheck if anything important about the local propertiesof a given class have changed since the last time theylooked. It does not increment on method/@ISAchanges in superclasses.

It's still up to you to seek out the actual changes,and there might not actually be any. Perhaps allof the changes since you last checked cancelled eachother out and left the package in the state it was inbefore.

This integer normally starts off at a value of 1when a package stash is instantiated. Calling iton packages whose stashes do not exist at all willreturn 0. If a package stash is completelydeleted (not a normal occurence, but it can happenif someone does something like undef %PkgName::),the number will be reset to either 0 or 1,depending on how completely package was wiped out.

next::method

This is somewhat like SUPER, but it uses the C3 methodresolution order to get better consistency in multipleinheritance situations. Note that while inheritance ingeneral follows whichever MRO is in effect for thegiven class, next::method only uses the C3 MRO.

One generally uses it like so:

  1. sub some_method {
  2. my $self = shift;
  3. my $superclass_answer = $self->next::method(@_);
  4. return $superclass_answer + 1;
  5. }

Note that you don't (re-)specify the method name.It forces you to always use the same method nameas the method you started in.

It can be called on an object or a class, of course.

The way it resolves which actual method to call is:

1

First, it determines the linearized C3 MRO ofthe object or class it is being called on.

2

Then, it determines the class and method nameof the context it was invoked from.

3

Finally, it searches down the C3 MRO list untilit reaches the contextually enclosing class, thensearches further down the MRO list for the nextmethod with the same name as the contextuallyenclosing method.

Failure to find a next method will result in anexception being thrown (see below for alternatives).

This is substantially different than the behaviorof SUPER under complex multiple inheritance.(This becomes obvious when one realizes that thecommon superclasses in the C3 linearizations ofa given class and one of its parents will notalways be ordered the same for both.)

Caveat: Calling next::method from methods defined outside the class:

There is an edge case when using next::method from within a subroutinewhich was created in a different module than the one it is called from. Itsounds complicated, but it really isn't. Here is an example which will notwork correctly:

  1. *Foo::foo = sub { (shift)->next::method(@_) };

The problem exists because the anonymous subroutine being assigned to the*Foo::foo glob will show up in the call stack as being called__ANON__ and not foo as you might expect. Since next::method usescaller to find the name of the method it was called in, it will fail inthis case.

But fear not, there's a simple solution. The module Sub::Name willreach into the perl internals and assign a name to an anonymous subroutinefor you. Simply do this:

  1. use Sub::Name 'subname';
  2. *Foo::foo = subname 'Foo::foo' => sub { (shift)->next::method(@_) };

and things will Just Work.

next::can

This is similar to next::method, but just returns either a codereference or undef to indicate that no further methods of this nameexist.

maybe::next::method

In simple cases, it is equivalent to:

  1. $self->next::method(@_) if $self->next::can;

But there are some cases where only this solutionworks (like goto &maybe::next::method);

SEE ALSO

The original Dylan paper

Pugs

The Pugs prototype Perl 6 Object Model uses C3

Parrot

Parrot now uses C3

Python 2.3 MRO related links

Class::C3

AUTHOR

Brandon L. Black, <[email protected]>

Based on Stevan Little's Class::C3

 
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 pragma to use or avoid PO ...Perl pragma to set default Per ... (Berikutnya)