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


In reply to Re^3: sorting tree with folders on top by jethro
in thread sorting tree with folders on top by diweooy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.