I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?
As usually with Perl, you might prefer alternative solutions to the venerable Data::Dumper:
And of course with the debugger, you can display any variable with the 'x' command. I particularly like the form 'x 2 $complex_structure
' where 2 (or any number) tells the debugger to display only 2 levels of nested data.
I went looking for the same thing and found this lovely little Perl function, explicitly meant to generate results like print_r().
The author of the script was asking your exact question in a forum here.
print objectToString($json_data);
Gives this output:
HASH {
time => 1233173875
error => 0
node => HASH {
vid => 1011
moderate => 0
field_datestring => ARRAY {
HASH {
value => August 30, 1979
}
}
field_tagged_persons => ARRAY {
HASH {
nid => undef
}
}
...and so on...
I use Data::Dump, it's output is a bit cleaner than Data::Dumper's (no $VAR1), it provides quick shortcuts and it also tries to DTRT, i.e. it will print to STDERR when called in void context and return the dump string when not.
Note @tchrist recommends Data::Dump over Data::Dumper. I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
Data::Dumper :
A snippet of the examples shown in the above link.
use Data::Dumper;
package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
package Fuz; # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};
package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
{1 => 'a', 023 => 'b', 0x45 => 'c'},
\\"p\q\'r", $foo, $fuz];
########
# simple usage
########
$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar); # pretty print (no array indices)
$Data::Dumper::Terse = 1; # don't output names where feasible
$Data::Dumper::Indent = 0; # turn off all pretty print
print Dumper($boo), "\n";
$Data::Dumper::Indent = 1; # mild pretty print
print Dumper($boo);
$Data::Dumper::Indent = 3; # pretty print with array indices
print Dumper($boo);
$Data::Dumper::Useqq = 1; # print strings in double quotes
print Dumper($boo);
An alternative to Data::Dumper that does not produce valid Perl code but instead a more skimmable format (same as the x
command of the Perl debugger) is Dumpvalue. It also consumes a lot less memory.
As well, there is Data::Dump::Streamer, which is more accurate in various edge and corner cases than Data::Dumper is.