I have an array full of hashes with paths to files or folders. I want to sort it naturally/alphabetically but to have folder on top, subfolder on top of the folder etc. same view like in windows explorer or some other file manager with all subfolders open.
my @arr = ( { 'path' => '/c/', dir => '/' }, { 'path' => '/c/a1.mp3', 'file' => 1, 'dir' => '/c' }, { 'path' => '/c/a2.mp3', 'file' => 1, 'dir' => '/c' }, { 'path' => '/c/bb/aa1.mp3', 'file' => 1, 'dir' => '/c/bb' }, { 'path' => '/c/bb/aa2.mp3', 'file' => 1, 'dir' => '/c/bb' }, { 'path' => '/c/bb/', 'dir' => '/c' }, { 'path' => '/c/cc/', 'dir' => '/c' }, { 'path' => '/c/aa/', 'dir' => '/c' } ); @arr = sort sort_files @arr; foreach (@arr) { my %h = %{$_}; print $h{'path'}."\n"; } # putting the folders on the top works, but... see output sub sort_files { # if both in the same folder and one is folder, put it top if ($$a{'dir'} eq $$b{'dir'}) { if ($$a{'file'} && !$$b{'file'}) { return 1; } elsif (!$$a{'file'} && $$b{'file'}) { return -1; } } # compare lc $$a{'path'} cmp lc $$b{'path'}; }
this is the output:
/c/ /c/aa/ /c/bb/ /c/cc/ /c/a1.mp3 <<<< file! it should at the end of the list /c/a2.mp3 <<<< file! should at the end of the list /c/bb/aa1.mp3 <<<< this should be below /c/bb/ /c/bb/aa2.mp3 <<<< this should be below /c/bb/
if I just sort it lexigraphicaly, it is sorted nicely, but the folders are not on the top of the parent folder. creative ideas?

In reply to 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.