How to print hash recursively?

P

Peng Yu

while ( ($k,$v) = each %hash ) {
print "$k => $v\n";
}

The above code would not print the content of $v, if $v points to
complex data structure such as arrays, hash of arrays, etc.

I'm wondering if there is a convenient function that can print a hash
table recursively into the elements.
 
J

Jürgen Exner

Peng Yu said:
while ( ($k,$v) = each %hash ) {
print "$k => $v\n";
}

The above code would not print the content of $v, if $v points to
complex data structure such as arrays, hash of arrays, etc.

I'm wondering if there is a convenient function that can print a hash
table recursively into the elements.

1: it is trivial to write your own
2: Did you check Data::Dumper?

jue
 
P

Peng Yu

I think you are looking for:

   perldoc Data::Dumper

If there are many keys in %hash, is there an option in Data::Dumper so
that only the first a few key value pairs are printed?
 
S

sreservoir

If there are many keys in %hash, is there an option in Data::Dumper so
that only the first a few key value pairs are printed?

there is no enumeration in a hash
 
C

C.DeRykus

...



If there are many keys in %hash, is there an option in Data::Dumper so
that only the first a few key value pairs are printed?

I don't know but you could easily partition out a few:

# tie my %hash, 'Tie::IxHash'; # to ensure ordering
# tie my %few, 'Tie::IxHash'; #

@few{(keys %hash)[0..4]}=(values %hash)[0..4]; # dump only 5
print Dumper \%few;
 
C

C.DeRykus

If there are many keys in %hash, is there an option in Data::Dumper so
that only the first a few key value pairs are printed?

I don't know but you could easily partition out a few:

  # tie my %hash, 'Tie::IxHash';  # to ensure ordering
  # tie my %few, 'Tie::IxHash';   #

  @few{(keys %hash)[0..4]}=(values %hash)[0..4]; # dump only 5
  print Dumper \%few;

For relatively simple hashes only though... more complexity
will probably frustrate attempts at satisfactory partitioning.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top