Schwartzian transform

Dermot paikkos at gmail.com
Wed Aug 13 10:33:50 BST 2014


Hi

Sorry for the OT post :)

I am trying to transform the hash reference below so that the value of
position is ordered from 1..4. The sorting works but I can't seem to modify
the value of {position} inline. To achieve what I want I have to look
through the @sorted array. I'd like to golf this if I can but I've hit a
wall.

Any suggestions?
Thanks,
Dermot.




use strict;
use warnings;
use Data::Dumper;

my $ref = {
          '603927' => {
                         'title' => 'Light and healthy picnic food',
                         'position' => 2,
                         'license' => 'F',
                         'id' => '603927'
                       },
          '562734' => {
                         'license' => 'M',
                         'position' => '0',
                         'title' => 'Man and woman beside highland loch in
rai',
                         'id' => '562734',
                       },
          '569368' => {
                         'license' => 'F',
                         'position' => '1',
                         'title' => 'A wooden picnic bench on the sand',
                         'id' => '569368',
                         'thumb' => '/image/569368/thumb'
                       },
           '193246' => {
                         'license' => 'F',
                         'position' => '5',
                         'title' => 'A wooden picnic bench on the sand',
                         'id' => '193246',
                         'thumb' => '/image/569368/thumb'
                       }
};

print Dumper ($ref);

my @sorted =
    map $ref->{$_->[0]},
#    map { $ref->{ $_->[0] }->{position} => $count++ }
    sort { $a->[1] <=> $b->[1] }
    map [ $_, $ref->{$_}->{position} ],
    keys %{ $ref };

print Dumper (\@sorted);

my $count = 1;
foreach my $hashref (@sorted) {
    $ref->{ $hashref->{id} }->{position} = $count++;
}
print Dumper ($ref);


More information about the london.pm mailing list