http://qs1969.pair.com?node_id=73984

I made small sub to generate the part of the HTML, a navigation bar to be exact, for a project I'm working on and I would like people to comment on it so I can learn from my mistakes and pick a few good pointer along the way.

Thanks!


This sub works by having a hash and an array passed to it. The hash is in a format Name => 'Link' were the Name is the part that shown in the html and the link this the URL that the name set to. If a link is set to '' it will not be displayed as a link. The array is to set the order of the hash is displayed in. The Array can be omitted in which case the Hash will be displayed in random order.

Here is the code,
sub NavB { my %Links = %{+shift}; my @LinkOrder = @{+shift}; my ($Trn, $TL); if (@LinkOrder) { for ( $TL=0; $TL <= $#LinkOrder; $TL++ ) { if ($Trn) { $Trn .= " -> "; } if ($Links{$LinkOrder[$TL]}) { $Trn .= "<a href=\"$Links{$LinkOrder[$TL]}\" target=\"_self\"> <font size=4 face=\"Arial, Helvetica, sans-serif\" color=6666cc>$Li +nkOrder[$TL]</font><\/a>"; } else { $Trn .= "$LinkOrder[$TL]"; } } } else { foreach $TL (sort(keys(%Links))) { if ($Trn) { $Trn .= " -> "; } if ($Links{$TL}) { $Trn .= "<a href=\"$Links{$TL}\" target=\"_self\"> <font size=4 face=\"Arial, Helvetica, sans-serif\" color=6666cc>$TL +</font><\/a>"; } else { $Trn .= $TL; } } } return "\n<font size=4 face=\"Arial, Helvetica, sans-serif\" color=666 +6cc>$Trn</font>\n"; }


------
The Price of Freedom is Eternal Vigilance

Replies are listed 'Best First'.
Re: Review.
by jepri (Parson) on Apr 20, 2001 at 06:09 UTC
    This is a great piece of code, but you are re-inventing the wheel a little. HTML::Template can put some complicated data structures into a HTML document.

    In your example you could just pass HTML::Template a LOH and it would interate over them, spitting out a navigation bar just the way you want.

    HTML::Template can also do if/then/else embedded in the HTML.

    This is usually easier for maintenance, since reading HTML that is in a Perl program is quite difficult.

    ____________________
    Jeremy
    I didn't believe in evil until I dated it.

Re: Review this HTML-generating code
by tadman (Prior) on Apr 20, 2001 at 08:47 UTC
    I agree with jepri's comments about not re-inventing the wheel, but when you're forced to, you might as well use a few tricks to make your life easier.

    In particular, when writing HTML, you can use single-quotes instead of double-quotes. Such as:     print "<A HREF='http://www.perlmonks.org'>Perl Monks</A>\n"; This will save you the agony of having to escape every double quote instance, which can add up to a lot of pain for large files.

      Or you can use qq{}, which allows interpolation but lets you use unescaped doublequotes. I'd go for using that all around instead of using single-quotes half the time.



      If God had meant us to fly, he would *never* have give us the railroads.
          --Michael Flanders