How do you sort the output of Data::Dumper?

qodeninja picture qodeninja · Sep 19, 2011 · Viewed 17.6k times · Source

I want to dump the values of my object and hash, but it keeps printing the keys out of order. How can I dump the keys in (recursive) sort-order?

use Data::Dumper;
print Dumper $obj;

Answer

socket puppet picture socket puppet · Sep 19, 2011

Set $Data::Dumper::Sortkeys = 1 to get Perl's default sort order. If you want to customize the order, set $Data::Dumper::Sortkeys to a reference to a subroutine that receives a reference to a hash as input, and outputs a reference to the list of the hash's keys in the order you want them to appear.

# sort keys
$Data::Dumper::Sortkeys = 1;
print Dumper($obj);

# sort keys in reverse order - use either one
$Data::Dumper::Sortkeys = sub { [reverse sort keys %{$_[0]}] };
$Data::Dumper::Sortkeys = sub { [sort {$b cmp $a} keys %{$_[0]}] };
print Dumper($obj);