Bill H said:
Is there a way in perl to dump all the variables used and their
current values to a file without printing everyone of them
individually?
Not easily. You'd have a chance with package variables. For
lexicals you'd need something like PadWalker, which is a bit
tricky to use.
Most people settle for printing selected values at selected
places for debugging. The module Data:
umper helps with
viewing complex data structures.
I have a module Report.pm in my private Perl library which
applies Data:
umper to a list of Perl expressions. I find
that I never use it, but I'm appending it anyway. It uses
a little-known feature to evaluate expressions in the caller's
context.
Anno
--------------------------------------------------------------------
package Report;
use strict; use warnings; # @^~`
use base 'Exporter';
our @EXPORT = qw( report);
{
# evaluate in caller context
package DB;
sub _reporter_report {
for my $expr ( @_ ) {
print Report::answer( $expr, eval $expr);
}
}
}
*Report::report = \ &DB::_reporter_report;
use Data:
umper ();
use Scalar::Util ();
sub answer {
my ( $expr, @val) = @_;
my $ans;
if ( $@ ) {
$ans = "$expr: $@" if $@;
$ans =~ s/ at \(eval .*$//;
} else {
if ( @val == 1 ) {
$ans = answer_scalar( $expr, @val);
} else {
$ans =join ', ' => map answer_scalar( $expr, $_), @val;
$ans = "($ans)";
}
}
$ans;
}
sub answer_scalar {
my ( $expr, $val) = @_;
my $ans;
if ( !defined $val ) {
$ans = "$expr = undef;\n";
} elsif ( ref $val ) {
( $ans = Data:
umper:
umper $val) =~ s/\$VAR1\b/$expr/g;
my $indent = ' ' x ( 8 + length( $expr) - length( '$VAR'));
$ans =~ s/^ {8}/$indent/mg;
} elsif (
Scalar::Util::looks_like_number( $val) or
ref( \ $val) eq 'GLOB'
) {
$ans = "$expr = $val;\n";
} else {
$ans = "$expr = '$val';\n";
}
$ans;
}
'@^~`'; # it's true
__END__
Use like this:
#!/usr/local/bin/perl
use strict; use warnings; $| = 1;
use Report;
my $x = 123;
my $y = [ qw( one two)];
my %z = (
hihi => [ 456, 789],
haha => { hoho => 'huhu'},
);
report qw( $x $y $z{haha});