Schwartzian transform

Damian Conway damian at conway.org
Wed Aug 13 11:42:02 BST 2014


If you only want to modify the original hash, you just need this:

    # Warning: map in void context used for side-effect of setting {position}...
    # (I feel so dirty! ;-)
    my $count = 1;
    map  { $_->[1]{position} = $count++ }
    sort { $a->[0] <=> $b->[0] }
    map  { [$_->{position}, $_] }
        values %{$ref};

If you actually want the @sorted array for some reason, you just need:

    # Warning: map has the side-effect of setting {position}...
    # (I still feel unclean!)
    my $count = 1;
    my @sorted = map  { $_->[1]{position} = $count++; $_->[1] }
                 sort { $a->[0] <=> $b->[0] }
                 map  { [$_->{position}, $_] }
                     values %{$ref};

But either way, you definitely need to document the side-effect in a comment,
so that it doesn't later turn into a bug.

Damian


More information about the london.pm mailing list