是否有一种合理的方法让一个perl6模块检查是否存在另一个perl6模块,并且当且仅当它被安装时才"使用"它?
像这样......
module Polygons;
if $available {
use Measure; #only if Measure is installed
}
class Rectangle is export {
has $.width;
has $.height;
method area {
$!width * $!height; #provides operator overload for Measure * Measure
}
}
#====================
module Measure;
class Measure is export {
has $.value;
has $.unit;
method Real {
$!value;
}
method Str {
"$!value $!unit";
}
method multiply( $argument ) {
my $result = $.;
$result.value = $!value * $argument;
$result.unit = "$!unit2";
return $result;
}
}
multi infix:<*> ( Measure:D $left, Measure:D $right ) is export {
return $result.multiply( $argument );
}
#====================
#main.p6
use Polygons;
use Measure;
my $x = Measure.new( value => 10, unit => 'm' );
my $y = Measure.new( value => 20, unit => 'm' );
my $rect = Rectangle.new( width => $x, height => y );
say $rect.area; #'200 m2'
Run Code Online (Sandbox Code Playgroud)
我们的想法是传播运算符重载(在这种情况下为infix:<*>)备份类继承,以便在属性中存储更复杂的对象.
(请不要撕毁排水沟 - 因为我怀疑总有办法!)
所以这个答案的第一个版本基本上没有用。
这是我想出的第一个新东西,它可以解决我所理解的你的问题。我还没有在回购上尝试过。
在一个文件中a-module.pm6:
unit module a-module;
our sub infix:<*> ($l,$r) { $l + $r } }
Run Code Online (Sandbox Code Playgroud)
这our意味着如果可以的话,我们将能够看到这个例程require,尽管它只能通过其完全限定名称可见&a-module::infix:<*>。
然后在使用文件中:
use lib '.';
try require a-module;
my &infix:<*> = &a-module::infix:<*> // &OUTER::infix:<*>;
say 1 * 2 # 2 or 3 depending on whether `a-module.pm6` is found
Run Code Online (Sandbox Code Playgroud)
如果模块丢失,则使用的默认例程可以是来自OUTER(如图所示)或来自CALLER或您喜欢的任何其他伪包的例程。
这个问题/解决方案看起来很基本,我怀疑它一定是在 SO 上或在文档中的某个地方。我将发布我所得到的内容,然后明天探索更多。