in reply to Sorting HoHoA based on Length of Second Key
This solution actually fails the test at the end, because the order it calculates disagrees with the order you specified, because it chose a different ordering for set2 and set3, which have the same "length." I think this failure is actually a good thing, because it reveals that there is no canonical ordering for the algorithm you want.
It would be interesting to either change the algorithm or rewrite the test so that you get an "ok." But I am going to skip that part. :)
#!/usr/bin/perl -w use strict; use warnings; use Test::More qw(no_plan); my $expected = 'set2 set3 set4 set1 '; my $HoHoA = { 'set1' => { 'AAAAAAA' => [ ['1','BOOK'],['2','PENCIL'] ], 'BBBBBBB' => [ ['0','CHALK'],['4','PEN'] ], }, # length of 2nd keys = 7 (all the same in 'set1') 'set2' => { 'AAA' => [ ['1','BOOK'],['2','PENCIL'] ], 'BBB' => [ ['0','CHALK'],['4','PEN'] ], }, # length of 2nd keys = 7 (all the same in 'set2') 'set3' => { 'AAA' => [ ['1','BOOK'],['2','PENCIL'] ], 'BBB' => [ ['0','CHALK'],['4','PEN'] ], }, # length of 2nd keys = 3 (all the same in 'set3') 'set4' => { 'AAAA' => [ ['1','BOOK'],['2','PENCIL'] ], 'BBBB' => [ ['0','CHALK'],['4','PEN'] ], }, # length of 2nd keys = 4 (all the same in 'set4') }; my $got = ''; foreach my $set ( sort { inner_key_length($a) <=> inner_key_length($b +) } ( keys %{$HoHoA} ) ) { $got = $got . "$set "; } sub inner_key_length { my $key = shift or die "no key"; my @keys = keys %{ $HoHoA->{$key} }; my $length_firstkey = length($keys[0]); for my $check_key ( @keys ) { die "inconsistent key length" unless $length_firstkey = lengt +h($check_key); } print "length $key is $length_firstkey\n"; return $length_firstkey; } is($got, $expected);
|
|---|