Data::Dumper::Simple with no source filter :)

Ovid on 2005-10-03T06:22:08

I think I should finalize this and publish this as Data::Dumper::Names.

#!/usr/bin/perl -l

use strict;
use warnings;

use Data::Dumper ();
use Scalar::Util 'refaddr';
use PadWalker 'peek_my';
sub Dumper {
    my $pad = peek_my(1);
    my %pad_vars;
    while (my ($var, $ref) = each %$pad) {
        $var =~ s/^[[:punct:]]/*/;
        $pad_vars{address($ref)} = $var;
    }
    my @names;
    my $varcount = 1;
    foreach (@_) {
        my $address = address($_);
        # Naive.  Expects they have no variables named /\$VAR\d+/
        push @names, exists $pad_vars{$address}
          ? $pad_vars{$address}
          : 'VAR' . $varcount++;
    }
    return Data::Dumper->Dump(\@_,\@names);
}

sub address {
    refaddr $_[0] ? $_[0] : \$_[0];
}

my $foo = 1;
my @bar = (2,3);
my @baz = (qw/this that/);

print Dumper($foo, \@bar, @baz);

my $baz = 18;
sub test_scope { print Dumper($baz) }
test_scope;
__END__
$foo = 1;
@bar = (
  2,
  3
);
$VAR1 = 'this';
$VAR2 = 'that';

$baz = 18;

It does require that you pass arrays and hashes as references, but I thought of a way around that, too (it would take a fair amount of work, though. I'd have to walk through individual variables to find the right ones) :)

Unfortunately there's an easily fixed bug in PadWalker which might cause grief for folks.


Re:

Aristotle on 2005-10-03T15:22:39

Yay! Told you it should be possible. :-)

Re:

Ovid on 2005-10-03T21:47:18

It still won't work for everyone, though. PadWalker is fragile and relies on undocumented features in Perl. As a result, it tends to break. I asked P5P if a patch to Data::Dumper was worth considering and the consensus is "no" for these reasons. Thus, I'll either be maintaining the source filtered version and this version side by side or I will figure out how to shoehorn this into Data::Dumper::Simple as an "optional" interface.

Re:

robin on 2005-10-05T22:17:26

PadWalker is fragile and relies on undocumented features in Perl.

That's true, but I do try to keep it working with new versions. I'm pretty confident that the latest version is the most reliable yet --especially now I've fixed the silly build problem that plagued the last two versions, thanks to Ovid telling me about it.

(Really PadWalker should be bundled with the core, then it would be allowed to rely on the internals of a particular perl. I'm not even sure I'm joking...)

Re:

Ovid on 2005-10-05T22:26:49

Actually, I'd be happy about PadWalker being bundled with the core but I doubt that's going to happen any time soon.