[sf-perl] JSON sorting question

Francisco Obispo fobispo at isc.org
Mon Nov 22 11:12:52 PST 2010


You shouldn't use $a or $b directly since they are not defined for the method sort_by.

try from 'perldoc JSON':

$json->sort_by(sub { lc $JSON::PP::a cmp lc $JSON::PP::b });

Francisco



On Nov 22, 2010, at 11:04 AM, David Alban wrote:

> greetings,
> 
> given the program:
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> 
> use lib '/nas/reg/lib/perl';
> 
> use JSON;
> 
> my $stuff = {
>  foo => {
>    baz => {
>      items => [
>        'Z',
>        'y',
>        'X',
>        'w',
>      ],
>    },
>    BAR => {
>      items => [
>        'c',
>        'a',
>        'D',
>        'B',
>      ],
>    },
>  },
> };
> 
> my $json = new JSON;
> 
> $json = $json->canonical( 1 );
> $json = $json->sort_by( sub { return lc( $a ) cmp lc( $b ) } );
> 
> my $json_text = $json->pretty->encode( $stuff );
> 
> print "$json_text\n";
> 
> output is:
> 
> Name "main::b" used only once: possible typo at junk.perl line 34.
> Name "main::a" used only once: possible typo at junk.perl line 34.
> {
>   "foo" : {
>      "baz" : {
>         "items" : [
>            "Z",
>            "y",
>            "X",
>            "w"
>         ]
>      },
>      "BAR" : {
>         "items" : [
>            "c",
>            "a",
>            "D",
>            "B"
>         ]
>      }
>   }
> }
> 
> 1. not sure how to get around the complaints about $a and $b.  this is
> a sort routine, yes?
> 
> 2. the result (of my real program, not this test program) will be a
> human editable file.  i want all items in lexigraphical order.  that
> is, i'd like the output to be ordered like:
> 
>  BAR
>    a
>    B
>    c
>    D
>  baz
>    w
>    X
>    y
>    Z
> 
> there will be a lot of data, and it would greatly reduce the effort of
> a person trying to determine if particular data exists in the file if
> the items are all sorted.  but i don't know how to accomplish this.
> 
> if i comment out the "$json = $json->sort_by( ... )" line, i get a
> little closer.  it sorts 'BAR' in front of 'baz' correctly, but
> doesn't modify the order of the "items":
> 
> {
>   "foo" : {
>      "BAR" : {
>         "items" : [
>            "c",
>            "a",
>            "D",
>            "B"
>         ]
>      },
>      "baz" : {
>         "items" : [
>            "Z",
>            "y",
>            "X",
>            "w"
>         ]
>      }
>   }
> }
> 
> what am i missing?
> 
> thanks,
> david
> -- 
> Live in a world of your own, but always welcome visitors.
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm

Francisco Obispo 
Hosted@ Programme Manager
email: fobispo at isc.org
Phone: +1 650 423 1374 || INOC-DBA *3557* NOC
Key fingerprint = 532F 84EB 06B4 3806 D5FA  09C6 463E 614E B38D B1BE






More information about the SanFrancisco-pm mailing list