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
source share