我有一些复杂的对象结构,我使用 Data::Printer 来检查它们。它不够有用的一种情况是:当一个对象(容器)具有另一个对象(子对象)的字段时,子对象仅作为类名出现在 DDP 的输出中。我还希望看到孩子的字符串化值。
让我们举个例子:
{
package Child;
use Moo;
use overload '""' => "stringify";
has 'value', is => 'ro';
sub stringify {
my $self = shift;
return "<Child:" . $self->value . ">";
}
}
{
package Container;
use Moo;
has 'child', is => 'ro';
}
my $child_x = Child->new(value => 'x');
print "stringified child x: $child_x\n";
my $child_y = Child->new(value => 'y');
print "stringified child y: $child_y\n";
my $container_x = Container->new(child => $child_x);
my $container_y = Container->new(child => $child_y);
use DDP;
print "ddp x: " . p($container_x) . "\n";
print "ddp y: " . p($container_y) . "\n";
输出:
stringified child x: <Child:x>
stringified child y: <Child:y>
ddp x: Container {
Parents Moo::Object
public methods (2) : child, new
private methods (0)
internals: {
child Child # <- note this
}
}
ddp y: Container {
Parents Moo::Object
public methods (2) : child, new
private methods (0)
internals: {
child Child # <- and this
}
}
如您所见,孩子在输出中无法区分。我想在那个地方看到字符串化,除了类名之外,或者代替类名。