I try to create a HTML table by hardcoding HTML mark-up in a Perl script. I get data from a text file and then split them up by component and print them out into a HTML table. Example of text file (author, book name, book content):
Ronnie Smith, javabook, javaclasses
Ronnie Smith, javabook, javamethods
Ronnie Smith, c-book, pointers
Carrlos Bater, htmlbook, htmltables
How do I just print the author name once instead of printing three times, and the same with the book name? Only one author, Ronnie Smith, wrote three books, so it should fall under one category. Also e.g. javaclasses and javamethods are from same book javabook, so we should have javabook printed only once.
My script:
use strict;
use warnings;
my $Author;
my $bookName;
my $bookContent;
my $bookContentList = "List.txt";
open MYFILE, $bookContentList or die "could not open $bookContentList \n";
my @body = "";
push(@body, "<html> \n");
push(@body, "<head> \n");
push(@body, "<TABLE BORDER=\"0\"\n");
push(@body, " <TD>");
push(@body, "<div align=\"left\"><Table border=1 bordercolor= \"black\"> \n");
push(@body, "<tr bgcolor=\"white\"><TH><b>Author</b></TH><TH>Book Name </TH><TH>bookContent</TH></TR>");
push(@body, "<br>\n");
while (<MYFILE>) {
($Author, $bookName, $bookContent) = split(",");
push(
@body, "<TR><td>$Author</TD>
<td>$bookName</TD>
<td>$bookContent</TD>"
);
}
push(@body, "</div></Table>");
my $Joining = join('', @body);
push(@body, "</body></font>");
push(@body, "</html>");
my $htmlfile = "compliance.html";
open(HTML, ">$htmlfile") || warn("Can not create file");
print HTML "$Joining";
close HTML;
close MYFILE;
This is a classic case for a hashtable: You want to identify an author and a book by unique identifiers:
I do not recommend the
push @bodymethod. But if you’re going to do it, I would recommendFile::Slurp.That way you also skip the mistake of joining
$Joiningtoo soon and failing to write out the footer, like you do.