Skip to content

Support for ordered hashes when tied with Tie::IxHash #69

@mrdvt92

Description

@mrdvt92

I don't want to break backwards compatibility but, it would be great if the hash keys were not sorted when the hash is tied to Tie::IxHash.

this works for me.

$ git diff
diff --git a/lib/YAML/Tiny.pm b/lib/YAML/Tiny.pm
index 9d519f7..3fef4b9 100644
--- a/lib/YAML/Tiny.pm
+++ b/lib/YAML/Tiny.pm
@@ -732,7 +732,9 @@ sub _dump_hash {
         die \"YAML::Tiny does not support circular references";
     }
     my @lines  = ();
-    foreach my $name ( sort keys %$hash ) {
+    my @names  = keys %$hash;
+    @names     = sort @names unless tied(%$hash);
+    foreach my $name ( @names ) {
         my $el   = $hash->{$name};
         my $line = ('  ' x $indent) . $self->_dump_scalar($name, 1) . ":";
         my $type = ref $el;

here's a test case

$ cat perl-YAML-Tiny-tied.pl
#!/usr/bin/perl
use strict;
use warnings;
use YAML::Tiny;
use Tie::IxHash;

tie my %output, 'Tie::IxHash', (c=>1, b=>2, a=>3);

print  YAML::Tiny->new(\%output)->write_string;

before

---
a: 3
b: 2
c: 1

after

---
c: 1
b: 2
a: 3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions