Save Perl YAML Order

I want to read data from a YAML file, but I need the order of the items to be saved.
Is there a module in perl that has this functionality and how to do it?


In response to @mugen kenichi

I managed to do what I want, but I do not think this is a reasonable decision.

old yaml:

foo: bar: some value baz: other value qwe: bar: yet another value baz: again 

new yaml

  - foo: bar: some value baz: other value - qwe: bar: yet another value baz: again 
+6
source share
1 answer

The YAML specification specifically indicates that "the mapping keys are not ordered" and that "in each case, when the order of the node is significant, the sequence should be used." To deduce the order from the display will be a violation of the specification. Using ordered mappings, as mentioned by mugen, is the right solution to maintain order.

If you really wanted to, you could somehow get a YAML parser to dump into Tie :: IxHash , which will keep order ... but I don't know any Perl YAML parsers that give you such a level of control. Perhaps you could do something with YAML :: Old :: Loader , but this is not a very good YAML parser, and YAML :: Old :: Loader is not documented.

A third option would be to use explicit YAML tags (aka types) to instruct the parser to load your mappings as a special type, and then you pass the callback ... but even then, most likely, the YAML parser will provide your callback with an unordered hash.

I would suggest you just change the YAML. The point of a portable data language is that all semantic meaning is explicitly specified in a data file or specification, not implied in a specific parser. Ordered mappings are the accepted, compact YAML idiom.

 - foo: bar: some value baz: other value - qwe: bar: yet another value baz: again 
+6
source

Source: https://habr.com/ru/post/895727/


All Articles