Embperl - building dynamic websites with Perl


How to Embed Perl Code in HTML Documents
[ << Prev: What is Embperl? ] [ Content ] [ Next: Dynamic Tables >> ]

Perl code can be embedded in three ways:



1.) [- ... -] Execute codetop
    [- $a = 5 -]  [- $b = 6 if ($a == 5) -]

The code between the [- and the -] is executed. No output will be generated in the HTML. This is mainly for assignments, function calls, database queries, etc.



2.) [+ ... +] Output the resulttop
    [+ $a +]  [+ $array[$b] +] [+ "A is $a" +]

The code between the [+ and the +] is executed and the return value (the value of the last expression evaluated) is output (sent to the browser in the HTML stream).



3.) [! ... !] Execute code oncetop
    [! sub foo { my ($a, $b) = @_ ; $a * $b + 7 } !]

Same as [- ... -], but the code is only executed for the first request. This is mainly for function definitions and one-time initialization.



Meta-Commandstop

Embperl support some meta commands to control the "program flow" within the Embperl document. This can be compared to preprocessor commands in C. The meta commands take the following form:

    [$ <cmd> <arg> $]
 

if, elsif, else, endif

 

The if command is just the same as in Perl. It is used to conditionally output/process parts of the document. Example:

 [$ if $ENV{REQUEST_METHOD} eq 'GET' $]
    This is a GET request
 [$ elsif $ENV{REQUEST_METHOD} eq 'POST' $]
    This is a POST request
 [$ else $]
    This is not GET and not POST
 [$ endif $]

This will output one of the three lines depending on the setting of $ENV{REQUEST_METHOD}.

 

while, endwhile

 

The while command can be used to create a loop in the HTML document. For example:

 [$ while ($k, $v) = each (%ENV) $]
    [+ $k +] = [+ $v +] <BR>
 [$ endwhile $]

The above example will display all environment variables, each terminated with a line break.

 

do, until

 

The do until also create a loop, but with a condition at the end. For example:

 [- @arr = (3, 5, 7); $i = 0 -]
 [$ do $]
    [+ $arr[ $i++ ] +]
 [$ until $i > $#arr $]
 

foreach, endforeach

 

Create a loop iterating over every element of an array/list. Example:

 [$ foreach $v (1..10) $]
    [+ $v +]
 [$ endforeach $]
 

var <var1> <var2> ...

 

By default, you do not need to declare any variables you use within an Embperl page. Embperl takes care of deleting them at the end of each request. Sometimes, though, you want to declare them explicitly. You can do this by using var:

 [$ var $a @b %c $]

Has the same effect as the Perl code:

 use strict ;use vars qw {$a @b %c} ;
 

hidden

 

hidden is used for creating hidden form fields and is described in the form field section below.


[ << Prev: What is Embperl? ] [ Content ] [ Next: Dynamic Tables >> ]


© 1997-2023 Gerald Richter / actevy