use Algorithm::C3;
# merging a classic diamond
# inheritance graph like this:
#
# <A>
# / \
# <B> <C>
# \ /
# <D>
my @merged = Algorithm::C3::merge(
'D',
sub {
# extract the ISA array
# from the package
no strict 'refs';
@{$_[0] . '::ISA'};
}
);
print join ", " => @merged; # prints D, B, C, A
Below is a brief explanation of C3 taken from the Class::C3 module. For more detailed information, see the ``SEE ALSO'' section and the links there.
<A>
/ \
<B> <C>
\ /
<D>
The standard Perl 5 MRO would be (D, B, A, C). The result being that A appears before C, even though C is the subclass of A. The C3 MRO algorithm however, produces the following MRO (D, B, C, A), which does not have this same issue.
This example is fairly trivial, for more complex examples and a deeper explanation, see the links in the ``SEE ALSO'' section.
{
package A;
sub supers {
no strict 'refs';
@{$_[0] . '::ISA'};
}
package C;
our @ISA = ('A');
package B;
our @ISA = ('A');
package D;
our @ISA = ('B', 'C');
}
print join ", " => Algorithm::C3::merge('D', 'supers');
The purpose of $func_to_fetch_parent is to provide a way for "merge" to extract the parents of $root. This is needed for C3 to be able to do it's work.
The $cache parameter is an entirely optional performance measure, and should not change behavior.
If supplied, it should be a hashref that merge can use as a private cache between runs to speed things up. Generally speaking, if you will be calling merge many times on related things, and the parent fetching function will return constant results given the same arguments during all of these calls, you can and should reuse the same shared cache hash for all of the calls. Example:
sub do_some_merging {
my %merge_cache;
my @foo_mro = Algorithm::C3::Merge('Foo', \&get_supers, \%merge_cache);
my @bar_mro = Algorithm::C3::Merge('Bar', \&get_supers, \%merge_cache);
my @baz_mro = Algorithm::C3::Merge('Baz', \&get_supers, \%merge_cache);
my @quux_mro = Algorithm::C3::Merge('Quux', \&get_supers, \%merge_cache);
# ...
}
------------------------ ------ ------ ------ ------ ------ ------ ------ File stmt bran cond sub pod time total ------------------------ ------ ------ ------ ------ ------ ------ ------ Algorithm/C3.pm 100.0 100.0 100.0 100.0 100.0 100.0 100.0 ------------------------ ------ ------ ------ ------ ------ ------ ------ Total 100.0 100.0 100.0 100.0 100.0 100.0 100.0 ------------------------ ------ ------ ------ ------ ------ ------ ------
Brandon L. Black, <blblack@gmail.com>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.