in reply to Re: sorting tree with folders on top
in thread sorting tree with folders on top

I was trying to follow 1) and 2), but I did not have much success:
sub sort_files { my $adir = $1 if $$a{path} =~ m/^(.*)\//; my $bdir = $1 if $$b{path} =~ m/^(.*)\//; # a and b in the same dir if ($adir eq $bdir) { if ($$a{'file'} && !$$b{'file'}) { return -1; } elsif (!$$a{'file'} && $$b{'file'}) { return 1; } return lc $$a{'path'} cmp lc $$b{'path'}; } # b in subdir of a if ($bdir =~/^$adir\// && $$a{'file'} && !$$b{'file'}) { return -1; # a in subdir of b } elsif ($adir =~/^$bdir\// && $$b{'file'} && !$$a{'file'}) { return 1; } lc $$a{'path'} cmp lc $$b{'path'}; }

Replies are listed 'Best First'.
Re^3: sorting tree with folders on top
by jethro (Monsignor) on Apr 07, 2009 at 15:31 UTC

    I got the right result with this code. I left my debug print statements in there so you can test some more. I'm not sure it gets all border cases. Interestingly the same-dir rule turned out to be a special case of the subdir rule (or not? Please test some more. Really)

    sub sort_files { print $$a{'path'},' - ', $$b{'path'}," : "; my $adir = $$a{'dir'}; my $bdir = $$b{'dir'};; # b in subdir of a if ($bdir =~/^$adir/ && $$a{'file'}) { print "dir 1\n"; return 1; # a in subdir of b } elsif ($adir =~/^$bdir/ && $$b{'file'}) { print "dir -1\n"; return -1; } # a and b in the same dir #if ($$a{'dir'} eq $$b{'dir'}) { # if ($$a{'file'} && !$$b{'file'}) { # print "f -1\n"; return -1; # } elsif (!$$a{'file'} && $$b{'file'}) { # print "f 1\n"; return 1; # } # } print " ",lc $$a{'path'} cmp lc $$b{'path'},"\n"; return lc $$a{'path'} cmp lc $$b{'path'}; }

    Note I changed your code so that $adir is simply $$a{'dir'} as it should be the same. Also put 2) before 1) and removed the condition in 2) that b should not be a file