I want to read data from a YAML file but I need the order of the elements to be preserved.
Is there a module in perl which has this functionality and how to do that?
In response to @mugen kenichi
I managed to do what I want but I don't believe that this is a reasonable solution.
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
UPDATE: YAML.pm now supports order preservation. See this up-to-date answer.
The YAML spec specifically states that "mapping keys do not have an order" and that "in every case where node order is significant, a sequence must be used". To infer order from a mapping would be in violation of the spec. Using ordered mappings, as mentioned by mugen, is the correct solution to preserve order.
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 supply the callback... but even then it's likely the YAML parser will supply your callback with an unordered hash.
I would suggest you simply change the YAML. The point of a portable data language is that all the semantic meaning is explicit in the data file or the spec, not implicit in a particular parser. Ordered mappings are an accepted, compact YAML idiom.
- foo:
bar: some value
baz: other value
- qwe:
bar: yet another value
baz: again
It is possible with YAML::PP since version 0.021.
use YAML::PP;
use YAML::PP::Common qw/ :PRESERVE /;
my $yp = YAML::PP->new( preserve => PRESERVE_ORDER );
my $data = $yp->load-string($yaml);
say $yp->dump_string($data);
(Disclaimer: I'm the module's author)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With