Data::Dumper numeric sort on first level key of HoH using Sortkeys sub

1.1k views Asked by At

I have a HoH data structure. The outer level hash's keys are numeric - so I'd like to Dump the HoH numerically sorted by the first hash key (I don't care about the order of the inner hash). I've been trying different Sortkeys subs:

use Data::Dumper;
#$Data::Dumper::Sortkeys = sub { [sort { $a <=> $b } (keys %{$_[0]})] };  ## A
 $Data::Dumper::Sortkeys = sub { [sort { $a <=> $b } keys %$_ ] };       ## B
print Dumper(\%dsCmdBlocks);

I can't find the right syntax in the Sortkeys subroutine that will dump the HoH sorted by the first key numerically. When I try "A", it's sorts it fine for the first key, but it also spits out error messages saying that the inner arguments are not numeric (which is due to the use of [0]). So "A" is not the correct way to go. But, I can't figure-out how to sort on the first hash only.

By the way, when I send the HoH through a normal foreach loop using this:

foreach my $sk (sort {$a<=>$b} keys %dsCmdBlocks)
{
 print "KEY: $sk\n";
}

it works as I would expect.

How can I set up my Sortkeys sub to only sort on the first hash key?

1

There are 1 answers

3
mob On BEST ANSWER

The callback for $Data::Dumper::Sortkeys operates on every hash reference found in the data structure, at any level. So you can either harden your sort routine against non-numeric inputs, like

$Data::Dumper::Sortkeys = sub {
    no warnings 'numeric';
    [ sort { $a <=> $b } keys %{$_[0]} ]
};

or apply some other machinations to see what your input looks like

$Data::Dumper::Sortkeys = sub {
    my $data = join '', keys %{$_[0]};
    if ($data =~ /[A-Za-z]/) {   # for example
        # input is not numeric
        return [keys %{$_[0]}];
    } else {
        return [ sort { $a <=> $b } keys %{$_[0]} ];
    }
};