my @array = ( 1, 2, 3, 4, 5, 6 ); my $func = sub { $_[0] <=> $_[1] }; my %tree = buildtree( $func, @array ); # the golf function # one possible output : %tree => { 2 => [ { 1 => [ 0, 0 ] } , { 4 => [ { 3 => [ 0, 0 ] }, { 5 => [ 0, { 6 => [ 0, 0 ] } ] } ] } ] }