1

I'm dumping a data structure to YAML with the YAML::XS library:

foo => {
    bar => [
        {...},
        {...},
    ],
    baz => [
        {...},
        {...},
    ], 
    ...
}

It seems like YAML::XS's default behavior is to sort the keys before dumping them, but this is not what I want. Humans will have to read and edit the output of this script, so readability is a concern. Is there a way to control the order that the keys are dumped out so that foo->{baz} would come before foo->{bar}?

Floegipoky
  • 3,087
  • 1
  • 31
  • 47
  • The docs are [here](http://search.cpan.org/perldoc?YAML::XS) – ikegami Jan 26 '15 at 20:44
  • 2
    You can do this using YAML.pm's [`Bless`](https://metacpan.org/pod/YAML#Bless-perl-node-yaml-node-class-name) but not sure if it's doable with YAML::XS. – ThisSuitIsBlackNot Jan 26 '15 at 20:48
  • @ikegami I read that already, it didn't answer my question – Floegipoky Jan 26 '15 at 20:55
  • 1
    @Floegipoky, It really does. – ikegami Jan 26 '15 at 20:58
  • 1
    @ThisSuitIsBlackNot I ended up swapping out `YAML::XS` for `YAML`, Thank you very much for pointing out the `Bless` feature. It's more powerful than I would have liked to use for this but it got the job done. For future viewers, be aware that unless you know at write-time exactly which keys you're expecting, you'll have to inspect each node that you're `Bless`ing. Also note that if a key is absent it will generate a dummy entry anyway, so make sure that you check for existence first: `my $blessarray = []; push $blessarray, 'optionalkey' if $table->{optionalkey}; `. – Floegipoky Jan 29 '15 at 16:44

1 Answers1

3

As you can see from the docs, there is no option that configures the order of hashes. This is further confirmed by looking at dump_node and dump_hash in LibYAML/perl_libyaml.c.

ikegami
  • 367,544
  • 15
  • 269
  • 518