in reply to Re-ordering data branches in a [Tree::DAG_Node] tree

G'day atcroft,

Here's a method using non-destructive transliteration. It requires 5.14 (see perl5140delta: Non-destructive substitution). The guts of the solution is:

sort { $a =~ y/ //dr cmp $b =~ y/ //dr } @data

I've tested with your OP data and tybalt's offering:

#!/usr/bin/env perl use 5.014; use warnings; my @test_data = ( [ atcroft => [ 'a', # ' b', # ' e', # ' f', # ' g', # ' c', # ' d', # 'h', # ' i', # ' j', # ]], [ tybalt => [ 'j', # ' i', # ' h', # ' g', # ' f', # ' e', # ' d', # 'c', # ' b', # ' a', # ]], ); say_sorted(@$_) for @test_data; sub say_sorted { my ($who, $data) = @_; say "Data from $who"; say '-' x 20; say for @$data; say '-' x 20; say for sort { $a =~ y/ //dr cmp $b =~ y/ //dr } @$data; say '=' x 20; }

Output:

Data from atcroft -------------------- a b e f g c d h i j -------------------- a b c d e f g h i j ==================== Data from tybalt -------------------- j i h g f e d c b a -------------------- a b c d e f g h i j ====================

— Ken

Replies are listed 'Best First'.
Re^2: Re-ordering data branches in a [Tree::DAG_Node] tree
by tybalt89 (Monsignor) on Apr 23, 2018 at 14:38 UTC

    My understanding is the tree structure should be preserved - only sibling nodes can be swapped to sorted order.
    For instance, node 'b' is a child of node 'c' in my original data, and should still be a node of 'c' in the result. It is not.

    I think the result should be

    c b a j e d h g f i