I am getting this error
Argument "\\x{61}" isn't numeric in numeric comparison (<=>)
from
#!/usr/bin/perl
use JSON::PP;
use utf8;
use strict;
use warnings;
use Data::Dumper;
my $json = JSON::PP->new->allow_nonref;
$json = $json->utf8;
my $data = {
12 => {
a => 1,
b => 2,
},
1 => {
x => 3,
},
2 => {
z => 4,
}
};
my $json_string = $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($data);
It is suppose to encode the hash to a json string, and then numeric sort the keys 12 1 2.
If the problem can be solved with another JSON parser, then that would be perfectly fine =)
What’s wrong?
If you prefer a numerical sort but want to fall back to a lexicographic sort, use this sort function:
When the sort keys are not numeric, the numerical comparison (
<=>) operator will return 0 and the function will perform the lexical comparison (cmp) operation.Edit (the above solution still didn’t suppress the warnings). A few more tweaks are needed to suppress the warnings. You could say