(编辑:pipe
下面的函数应该返回一个受祝福的对象,以便重载正常工作。请参阅接受的答案。)
我正在尝试使用 perl 的overload
功能来构建一个简单的解析树。我不需要太多——事实上,我只需要一个左结合运算符。但是 perl 解析的方式$x op $y
与较长的链(如$x op $y op $z op ...
.
这是我所拥有的:
package foo;
use overload '|' => \&pipe,
"**" => \&pipe,
">>" => \&pipe;
sub pipe { [ $_[0], $_[1] ] }
package main;
my $x = bless ["x"], "foo";
my $y = bless ["y"], "foo";
my $z = bless ["z"], "foo";
my $w = bless ["w"], "foo";
# how perl parses it:
my $p2 = $x | $y; # Cons x y
my $p3 = $x | $y | $z; # Cons z (Cons x y)
my $p4 = $x | $y | $z | $w; # Cons w (Cons z (Cons x y))
my $p5 = $z | ($x | $y); # same as p3???
my $s2 = $x ** $y; # Cons x y
my $s3 = $x ** $y ** $z; # Cons x (Cons y z)
my $s4 = $x ** $y ** $z ** $w; # Cons x (Cons y (Cons z w))
sub d { Dumper(\@_) }
say "p2 = ".d($p2);
say "p3 = ".d($p3);
say "p4 = ".d($p4);
say "p5 = ".d($p5);
say "s2 = ".d($s2);
say "s3 = ".d($s3);
say "s4 = ".d($s4);
输出类似于:
p2 = [bless( ['x'], 'foo' ),bless( ['y'], 'foo' )]
p3 = [bless( ['z'], 'foo' ),[bless( ['x'], 'foo' ),bless( ['y'], 'foo' )]]
p4 = [bless( ['w'], 'foo' ),[bless( ['z'], 'foo' ),[bless( ['x'], 'foo' ),bless( ['y'], 'foo' )]]]
p5 = [bless( ['z'], 'foo' ),[bless( ['x'], 'foo' ),bless( ['y'], 'foo' )]]
s2 = [bless( ['x'], 'foo' ),bless( ['y'], 'foo' )]
s3 = [bless( ['x'], 'foo' ),[bless( ['y'], 'foo' ),bless( ['z'], 'foo' )]]
s4 = [bless( ['x'], 'foo' ),[bless( ['y'], 'foo' ),[bless( ['z'], 'foo' ),bless( ['w'], 'foo' )]]]
不应该p2
将 x 和 y 颠倒以与其他情况一致吗?请注意p3
并p5
产生相同的输出 - 那么我如何区分它们呢?
我没有看到与右关联运算符相同的问题**
。
有解决办法吗?