Tuesday, April 27, 2010

Dumper and sorting of keys

When you use Dumper for debugging via comfortable logging data structures by reference, you can additionally apply sorting to the output. Say, you have a hash addressed by $hash_ref reference. If you need to output the hash contents, but have its keys sorted, you can do:

  1. use strict;  
  2. use Data::Dumper;  
  3.   
  4. $hash_ref = generate your hash here  
  5.   
  6. $Data::Dumper::Sortkeys = \&my_filter;  
  7. print Dumper($hash_ref), "\n";  
  8.   
  9. sub my_filter {  
  10.  my ($hash) = @_;  
  11.  # return an array ref containing the hash keys to dump  
  12.  # in the order that you want them to be dumped  
  13.         return [  
  14.             sort {$a <=> $bkeys %$hash  
  15.         ];  
  16. }