Home > Software engineering >  How to sort output from Data::Printer?
How to sort output from Data::Printer?

Time:10-28

I'm attempting to sort output from Data::Printer and having no luck. I would like to sort numerically by value, instead of alphabetically by key (which is default).

inspired by How do you sort the output of Data::Dumper? I'm guessing that Data::Printer's sort_methods works similarly to Data::Dumper's Sortkeys:

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use autodie ':default';
use DDP {output => 'STDOUT', show_memsize => 1};

my %h = (
    'a' => 0,
    'b' => 7,
    'c' => 5
);
p %h, sort_methods => sub { sort {$_[0]->{$b} <=> $_[0]->{$a}} keys %{$_[0]} };

but this prints out

{
    a   0,
    b   7,
    c   5
} (425B)

but the order should be b, c, and then a. Curiously, there is no error message.

How can I sort the output of Data::Printer numerically by hash value?

CodePudding user response:

You're not dumping an object, so sort_methods doesn't apply. And if it did, "this option will order them alphabetically".

There is a sort_keys option for hashes, but it determines "Whether to sort keys when printing the contents of a hash". It defaults to 1, and there's no mention of a means to set the order. A test confirms that providing a sub doesn't provide a means to provide a sort order.

$ perl -e'use DDP; p {a=>5}->%*, sort_keys => sub { };'
[Data::Printer] 'sort_keys' property must be a scalar, not a reference to CODE at -e line 1.
  • Related