Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; 
like image 221
qodeninja Avatar asked Sep 19 '11 05:09

qodeninja


2 Answers

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); 
like image 90
socket puppet Avatar answered Sep 23 '22 04:09

socket puppet


Short answer for the impatient

Use Data::Dumper::Concise instead. It sorts your keys. Use it like this:

use Data::Dumper::Concise;  my $pantsToWear = {     pony       => 'jeans',     unicorn    => 'corduroy',     marsupials => {kangaroo => 'overalls', koala => 'shorts + suspenders'}, };  warn Dumper($pantsToWear); 

More words for the curious

Data::Dumper::Concise also gives you more compact, easier to read output.

Note that Data::Dumper::Concise is Data::Dumper with reasonable default configuration values set for you. Its equivalent to using Data::Dumper like this:

use Data::Dumper; {   local $Data::Dumper::Terse = 1;   local $Data::Dumper::Indent = 1;   local $Data::Dumper::Useqq = 1;   local $Data::Dumper::Deparse = 1;   local $Data::Dumper::Quotekeys = 0;   local $Data::Dumper::Sortkeys = 1;   warn Dumper($var); } 
like image 39
Eric Johnson Avatar answered Sep 23 '22 04:09

Eric Johnson