Re: easiest way to print the content of a hash?
by ptum (Priest) on Jul 13, 2006 at 15:33 UTC
|
There's always Data::Dumper.
Or, assuming your hash values are scalars, you can step through the keys and print out the contents, like this:
foreach (sort keys %myhash) {
print "$_ : $myhash{$_}\n";
}
No good deed goes unpunished. -- (attributed to) Oscar Wilde
| [reply] [d/l] |
|
I can never quite get why nobody (apart from me) ever seems to recommend Data::Dumper::Simple for debugging?
It's way easier to use than Data::Dumper, especially for more complex data structures. There is no need to pass references, and the output contains the actual variable names - instead of "VAR1", "VAR2", etc.
I know you can get the same thing with Data::Dumper using Dumper->Dump, but this can very quickly become quite unwieldy.
About the only objection I could imagine to using Data::Dumper::Simple is that is uses source filters, but if you're only using it for debugging - and not in production code - what's the problem?
Just curious....
Darren :)
| [reply] |
|
Perhaps because it's a source filter? (Yes, I read your post. And yes, that's my reason.)
| [reply] |
|
| [reply] [d/l] [select] |
|
use Data::Dumper;
my %hash = (
key1 => 'value1',
key2 => 'value2'
);
print Dumper(%hash); # okay, but not great
print "or\n";
print Dumper(\%hash); # much better
And the output:
$VAR1 = 'key2';
$VAR2 = 'value2';
$VAR3 = 'key1';
$VAR4 = 'value1';
or
$VAR1 = {
'key2' => 'value2',
'key1' => 'value1'
};
| [reply] [d/l] [select] |
Re: easiest way to print the content of a hash?
by marto (Cardinal) on Jul 13, 2006 at 15:38 UTC
|
| [reply] |
|
thanks for the suggestions.
data::dumper looks good to me.
I've used the foreach, of course, but that's messy for a quick output.
| [reply] |
Re: easiest way to print the content of a hash?
by davido (Cardinal) on Jul 13, 2006 at 17:39 UTC
|
If you don't like the output of Data::Dumper and just want a simple key/value dump (without any deep datastructure exploration), you could apply this function:
sub print_hash {
my $href = shift;
print "$_\t=> $href->{$_}\n" for keys %{$href};
}
It could also be written like this:
sub print_hash {
my $href = shift;
while( my( $key, $val ) = each %{$href} ) {
print "$key\t=>$val\n";
}
}
| [reply] [d/l] [select] |
Re: easiest way to print the content of a hash?
by coreolyn (Parson) on Jul 13, 2006 at 17:32 UTC
|
If you're just doing a quick check on the contents of a hash nothing beats print "\%hash = @{[%hash]}\n"; for debugging.
| [reply] [d/l] |
Re: easiest way to print the content of a hash?
by planetscape (Chancellor) on Jul 17, 2006 at 06:20 UTC
|
| [reply] |
Re: easiest way to print the content of a hash?
by Anonymous Monk on Mar 03, 2016 at 15:24 UTC
|
map{print "$_\t$hash{$_}\n"}keys %hash; | [reply] |