[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] nested lists of hierarchical structures



I cam across an interesting problem the other day:
I had a sorted bunch of newsgroup names, and I wanted to format them 
as a list of lists where each newsgroup would be as deep in 
the list as it was in the hieararchy.

i.e, I wanted something like:
<ul>
  <li>si
  <ul>
    <li>si/misc
    <ul>
       <li>si/misc/admin
    </ul>
    <ul>
      <li>si/misc/talk
    </ul>
  </ul>
  <li>si/sci
</ul>

You get the idea.

So I came up with:

sub listhand {
    my $outstr;
    my ($previous,$str)=@_;
    my $common="";
    $outstr="<ul>" if ($previous eq "");
    while ($previous=~m!^($common/?[^/]*)!) {
        last if index($str,$1);
        last if $common eq $previous;
        $common=$1;
    }
    $rest=substr($previous,length($common));
    $outstr.= "</ul>\n" x ($rest=~tr!/!/!);
    
    $rest=substr($str,length($common));
    $outstr.= "<ul>\n" x ($rest=~tr!/!/!);
    $outstr.="</ul>" if ($str eq "");
    $_[0]=$_[1];                 # change the value of parameter in caller, too
    return $outstr;
}


Which enables me to basicaly do:
$previous="";
foreach (@dirs) {
    print MAINIDX listhand($previous,$_);
    print MAINIDX "<LI>$_\n";
}
print MAINIDX listhand($previous,"");

(There's a lot more in the loop, but you get the idea).
I rather like the method to climb up and down the hierarchy, but I was 
wondering if there was an even more elegant method of doing this that I 
was overlooking.


-- 
"My name is Not Important. Not to friends. 
    But you can call me mr. Important"  - Not J. Important 
Matija.Grabnar@arnes.si



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe