【问题标题】:How to make Data::Printer show stringified values in internals?如何使 Data::Printer 在内部显示字符串化值?
【发布时间】:2013-07-02 22:20:00
【问题描述】:

我有一些复杂的对象结构,我使用 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
    }
}

如您所见,孩子们在输出中无法区分。我想在那个地方看到字符串化,除了类名之外,也可以代替类名。

【问题讨论】:

    标签: perl formatting ddp


    【解决方案1】:

    the Data::Printer docs

    Data::Printer 让您能够使用过滤器覆盖任何 一种数据显示。过滤器放置在散列上,其中键位于 类型 - 或类名 - 和值是匿名子 接收两个参数:项目本身作为第一个参数,以及 属性 hashref (以防您的过滤器想要从中读取)。这个 让您快速覆盖 D​​ata::Printer 处理和显示的方式 数据类型,尤其是对象。

    【讨论】:

    • 感谢您让我走上正轨。我也注意到了这一段,但由于某种原因,我认为使用此功能会很困难,但事实并非如此。我将通过一个示例发布答案以供后人参考。
    【解决方案2】:

    正如 Dave 指出的,我们可以在导入 Data::Printer 时定义过滤器:

    use DDP filters => {
        'Child' => sub { "$_[0]" }
    };
    

    甚至更好的方法是使用_data_printer 功能(因为每次导入 DDP 时都要输入过滤器定义很痛苦):

    {
        package Child;
        ...
    
        sub _data_printer {
            my $self = shift;
            return "$self";
        }
    }
    

    两种方式都在内部显示字符串化的值:

    ddp x: Container  {
        Parents       Moo::Object
        public methods (2) : child, new
        private methods (0)
        internals: {
            child   <Child:x>
        }
    }
    

    【讨论】:

    • _data_printer 实际上是我首先在文档中寻找的内容,但我从未真正使用过它,并且不确定它是否适用于子对象或仅适用于父对象。现在我知道了 - 谢谢!
    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2011-07-28
    • 2019-06-29
    • 2020-10-03
    相关资源
    最近更新 更多