1

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?

con
  • 5,767
  • 8
  • 33
  • 62
  • Re "*I'm guessing that Data::Printer's `sort_method` works similarly to Data::Dumper's `Sortkeys`*", Where do you see `sort_method`? – ikegami Oct 27 '21 at 17:57
  • @ikegami that's a typo, I corrected to `sort_methods` which does appear in https://metacpan.org/pod/Data::Printer the hash still prints in the wrong order, however – con Oct 27 '21 at 17:58
  • You're not dumping an object, so `sort_methods` doesn't apply. And if it did, "*this option will order them alphabetically*" – ikegami Oct 27 '21 at 18:00
  • The `sort_methods` has nothing to do with sorting actual data. It's about how to show methods etc – zdim Oct 27 '21 at 18:01
  • 1
    Looks like you'd have to dig into filters, via [Data::Printer::Filter](https://metacpan.org/pod/Data::Printer::Filter) – zdim Oct 27 '21 at 18:14

1 Answers1

2

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.
ikegami
  • 367,544
  • 15
  • 269
  • 518