Arrays and functions: Format conversions

  1. A smarter join
  2. Arrays and functions
  3. The current script

It is now very easy to add new formats. One common use of Perl is to convert data into HTML. Our song listings could just as easily be turned into HTML table rows for insertion into an HTML table.

First, add a new format called “html” to @validFormats.

@validFormats = ("raw", "simple", "html", "summary");

Second, add a new “elsif” to the part of the script that displays the data:

} elsif ($format eq "html") {
print "<tr><td>$song</td><td>$album</td><td>$artist</td></tr>\n";

Now, repeat some of your previous searches, but ask for the format to be html instead. The data will be displayed in rows that could be included as part of a web page:

./show --album yellow --song girl --format html songs.txt

<tr><td>Young Girl Blues</td><td>Mellow Yellow</td><td>Donovan</td></tr>
<tr><td>Dirty little girl</td><td>Goodbye Yellow Brick Road</td><td>Elton John</td></tr>
<tr><td>All the girls love Alice</td><td>Goodbye Yellow Brick Road</td><td>Elton John</td></tr>

If your web server supports server-side includes, you can automatically include this in your web page. Write it to a file using “>” redirection and include that file.

  1. A smarter join
  2. Arrays and functions
  3. The current script