in reply to Dumping opaque objects

...Freezer = 'stringify'; local *UNIVERSAL::stringify = sub { $_[0]->isa('Math::GMP') ? "$_[0]" : $_[0] }; ...Dumper...

Replies are listed 'Best First'.
Re^2: Dumping opaque objects
by hv (Prior) on Jan 24, 2022 at 00:42 UTC

    Sadly that doesn't appear to do what I want (though I'd love it to): the docs for $Data::Dumper::Freezer talk only about modifying the object passed in, not about a return value. And indeed, trying it (with a different name to avoid the existing Math::GMP::stringify method) shows it is called but has no effect on the Data::Dumper output:

    % perl -MData::Dumper -MMath::GMP -wle ' $Data::Dumper::Freezer = "zify"; local *UNIVERSAL::zify = sub { warn "zify $_[0]"; $_[0]->isa("Math:: +GMP") ? "z$_[0]" : $_[0] }; my $x = [ Math::GMP->new(1) ]; print "x[0]=$x->[0]"; print Dumper($x); print "x[0]=$x->[0]"; ' Name "UNIVERSAL::zify" used only once: possible typo at -e line 3. x[0]=1 zify 1 at -e line 3. $VAR1 = [ bless( do{\(my $o = 40040032)}, 'Math::GMP' ) ]; x[0]=1

    If I change it to assign back to $_[0] instead, Dumper outputs garbage ("\undef") and the data structure is corrupted to have the new string instead of the original object:

    % perl -MData::Dumper -MMath::GMP -wle ' $Data::Dumper::Freezer = "zify"; local *UNIVERSAL::zify = sub { warn "zify $_[0]"; $_[0]->isa("Math:: +GMP") ? "z$_[0]" : $_[0] }; my $x = [ Math::GMP->new(1) ]; print "x[0]=$x->[0]"; print Dumper($x); print "x[0]=$x->[0]"; ' Name "UNIVERSAL::zify" used only once: possible typo at -e line 1. x[0]=1 zify 1 at -e line 1. $VAR1 = [ \undef ]; x[0]=z1
      Hi hv,

      I was able to get a Dumper() that appears more meaningful (to me, at least) with:
      ## dumper.pl ## use strict; use warnings; use Data::Dumper; use Math::GMP; my $x = [ Math::GMP->new(101), Math::GMP->new(203), Math::GMP->new(116 +7) ]; print Dumper("@$x"); __END__ C:\_32\pscrpt>perl dumper.pl $VAR1 = '101 203 1167';
      However, I'm not familiar with Data::Dumper and I've no idea if that's of any use to you.

      Cheers,
      Rob

        Thanks Rob, that's essentially the sort of thing I currently need to do, but it requires knowing the exact structure to be dumped and walking it myself. I also want to distinguish between GMP objects and simple integers - particularly to spot when something that should be GMP is not or v.v. - so I'd end up needing to write most of Data::Dumper myself. I had hoped somebody would already have done that for me (and that someone here would have used it).

        My CPAN-fu is minimal, but of the 2,520 matches on metacpan for 'dump', a quick scan of the first 100 threw up some maybes such as Data::Printer (which cares mostly about coloured output) and Data::Dump::Streamer (which cares mostly about structure recreatability via eval). I also spotted a cross-reference to Data::Rmap, which might offer a sane way to roll my own. I'll try some of those and see what I get.