How to Embed Perl in HTML
The convenience of embedding scripting code in HTML documents for web development is undeniable. Having a powerful language like Perl working just like PHP is a very good combination. Embedding Perl in HTML allows for many different things to happen inside a web page, from table creation to drawing content from a database of articles. You can embed Perl in HTML by installing extra software packages or using the software you already have.
Instructions
-
Use Heredoc to Embed Perl
-
1
Write your HTML code in a "heredoc" quote. This is a quick way to embed Perl without the need for additional software. This type of quote (like a double or a single quote) is best for quoting very long, multiline strings. Simply encompass your HTML in these heredoc quotes, remembering the newline after the final END keyword:
"print <
Title
END" -
2
Add interpolated variables. Heredocs can have interpolated variables just like double quotes:
"$title = "My cool webpage";
print <$title
END
" -
-
3
Add loops, as the same heredoc can be looped over multiple times. In this example, loop will print the numbers 1 through 10 in a table.
"print <
ENDfor( $i = 1; $i <= 10; $i++ ) {
print <$i
END
}print <
END
"
Use an Embedded Perl Interpreter
-
4
Install HTML::Embperl. This package can be installed via CPAN and configured to work with mod_perl and Apache.
-
5
Write a skeleton HTML document for testing:
"
test
Content goes here
" -
6
Execute Perl code. This is just one of the meta-tags, and will execute perl code and produce no output. It should be used for variable assignment, loops and any other code that produces no output:
"[- $a = 10 -]" -
7
Produce output from Perl. The meta-tags will print anything within them, which is useful for outputting a variable:
"$a = [+ $a +]
" -
8
Put it all together. Here is the table example with the embedded perl meta-tags:
"
"
[- for( $i = 1; $i <= 10; $i++ ) { -]
[+ $i +]
[- } -]
-
1
Tips & Warnings
Starting and stopping the heredocs can be cumbersome. This is not the case with an embedded Perl interpreter.