=pod
I've got an array that I want to sort in a tree-like fashion. Each element consists of a hashref with a path and label node. These should be sorted by path, but elements in the same "directory" should be sorted alphabetically. Here's an example data structure:
=cut
@r = (
{ path => './001', label => 'base' },
{ path => './001/001', label => 'last' },
{ path => './001/002', label => 'first' },
{ path => './001/002/001', label => 'last' },
{ path => './001/002/002', label => 'first' },
{ path => './002', label => 'second' },
{ path => './002/001', label => 'last' },
{ path => './002/002', label => 'first' },
{ path => './003', label => 'third' },
{ path => './004', label => 'fourth' },
);
=pod
As you can see, this is sorted by path, But I'd like it sorted like this:
@s = (
{ path => './001', label => 'base' },
{ path => './001/002', label => 'first' },
{ path => './001/002/002', label => 'first' },
{ path => './001/002/001', label => 'last' },
{ path => './004', label => 'fourth' },
{ path => './001/001', label => 'last' },
{ path => './002', label => 'second' },
{ path => './002/002', label => 'first' },
{ path => './002/001', label => 'last' },
{ path => './003', label => 'third' },
);
So basically: sort items with the same path component (that is, everything except what's after the last /) alphabetically, otherwise sort by full path.
But I can't seem to get it right.
Start Free Trial