Home : Documentation : 1.3.6 documentation : HTML::Embperl
Google Web perl.apache.org

1.3.6 documentation
Tips & Tricks
More infos
Add info about Embperl

    Stable 2.4.0
    Beta 2.5.0_3
Support the development of Embperl! More...
[ << Prev: Runtime configuration ] [ Content ] [ Next: Variable scope and cleanup >> ]

Embperl understands two categories of commands. The first one are special Embperl commands, and the second category consists of some HTML tags which can trigger special processing. Embperl commands can span multiple lines and need not start or end at a line boundary.

Before the special Embperl commands are processed, and for the VALUE attribute of the INPUT tag (see below), all HTML tags are removed and special HTML characters are translated to their ASCII values (e.g., `&lt;' is translated to `<'). You can avoid this behavior by preceding the special character or HTML tag with a backslash. This is done in case your favorite (WYSIWYG) HTML editor inserts tags like line breaks or formatting into your Embperl commands where you don't want them.

VERY IMPORTANT NOTE: If you do use an ASCII editor to write your HTML documents, you should set the option optRawInput so that Embperl does not preprocess your source. You can also HTML-escape your code (i.e. write `&lt;' instead of `<'), to avoid ambiguity. In most cases it will also work without the optRawInput and HTML-escaping, but in some cases Embperl will detect an HTML tag were there isn't one.

If you have any trouble with your code, especially with HTML tags or filehandles in your Perl code, be sure to understand input- and output- escaping and unescaping. Read the section L<"Inside Embperl"|"Inside Embperl - How the embedded Perl code is actually processed" to see what's going on!!>

All Embperl commands start with a `[' and end with a `]'. To get a real `[' you must enter `[['.

Embperl does not use SGML comments (i.e., <! ... !> or similar things) because some HTML editors can't create them, or it's much more complicated. Since every HTML editor takes (or should take) `[' and `]' as normal text, there should be no problem.

[+ Perl code +]top

Replace the command with the result you get from evaluating the Perl code. The Perl code can be anything which can be used as an argument to a Perl eval statement. (See (Safe-)Namespaces and opcode restrictions below for restrictions.) Examples:

 [+ $a +]        Replaces the [+ $a +] with the content of
                 the variable $a

 [+ $a+1 +]      (Any expression can be used)

 [+ $x[$i] +]    (Arrays, hashes, and more complex
                 expressions work)

NOTE: Whitespace is ignored. The output will be automatically HTML-escaped (e.g., `<' is translated to `&lt;') depending on the value of the variables $escmode. You do not have to worry about it.

[- Perl code -]top

Executes the Perl code, but deletes the whole command from the HTML output.


 [- $a=1 -]            Set the variable $a to one.
 		       No output will be generated.

 [- use SomeModule ;  -]  You can use other modules. NOTE the semicolon!

 [- $i=0; while ($i<5) {$i++} -]  Even more complex
                                  statements or multiple
                                  statements are possible.

NOTE: Statements like if, while, for, etc., must be contained in a single Embperl command. You cannot have the if in one command block and the terminating `}' or else in another.

NOTE: To define subroutines, use [! Perl Code !] (see below) instead of [- ... -] to avoid recompilation of the subroutine on every request.

[! Perl Code !]top

Same as [- Perl Code -] with the exception that the code is only executed at the first request. This could be used to define subroutines, or do one-time initialization.

[* Perl code *]top

(only version 1.2b2 or higher) EXPERIMENTAL!

This is similar to [- Perl Code -]. The main difference is, while [- Perl Code -] always has its own scope, all [* Perl code *] blocks runs in the same scope. This allows you to define "local" variables with a scope of the whole page. Normally, you don't need to use local, because Embperl takes care of separate namespaces of different documents and cleanup after the request is finished, but in special cases it's necessary. For example, if you want to recursively call an Embperl document via Execute.

There is a second reason to use the [* Perl code *] instead of the [- Perl Code -]. If you like to use perl's control structures. Perl's if, while, for etc. can not span mulitple [- Perl Code -] blocks, but it can span multiple [* Perl Code *].


  [* foreach $i (1..10) { *]
    [- $a = $i + 5 -]
    loop count + 5 = [+ $a +] <br>

  [* } *]

  The following B<won't> work:

  [- foreach $i (1..10) { -]
    some text here <br>
  [- } -]

The same can be done with Embperl meta commands (see below)

  [$ foreach $i (1..10) $]
    [- $a = $i + 5 -]
    loop count + 5 = [+ $a +] <br>

  [$ endforeach $]

NOTE 1: [* ... *] blocks _must_ always end with a ;,{ or }

NOTE 2: [* ... *] cannot apear inside a html tag that is interpreted by Embperl (unless you disable the interpretation of such tags like table, input etc.)

NOTE 3: There are still benefits of using [- ... -] and metacommands: - much better debugging in the log file. - no restriction on where they can be used. You can use them anywhere; even inside html tags that are interpreted by Embperl.

[# Some Text #] (Comments)top

(only version 1.2b2 or higher)

This is a comment block. Everything between the [# and the #] will be removed from the output.

NOTE 1: The [* ... *] blocks are interpreted before the comment block, so they are executed also inside a comment.

NOTE 2: Everything (except [* ... *]) is really removed from the source, so you can also use the [# ... #] block to take a part out of your document.

[$ Cmd Arg $] (Meta-Commands)top

Execute an Embperl metacommand. Cmd can be one of the following. (Arg varies depending on <Cmd>).


if, elsif, else, endif


Everything following the if metacommand until the else, elsif, or endif is only output if the Perl expression given in Arg is true. else and elsif work similarly.


 [$ if $ENV{REQUEST_METHOD} eq 'GET' $]
 Method was GET<BR>
 [$ else $]
 Method other than GET used<BR>
 [$ endif $]

This will send one of the two sentences to the client, depending on the request method used to retrieve the document.


while, endwhile


Executes a loop until the Arg given to while is false.

Example: (see eg/x/loop.htm)

 [- $i = 0; @k = keys %ENV -]
 [$ while ($i &lt; $#k) $]
 [+ $k[$i] +] = [+ $ENV{$k[$i]} +]<BR>
 [- $i++ -]
 [$ endwhile $]

This will send a list of all environment variables to the client.

NOTE: The `&lt;' is translated to `<' before calling Perl eval, unless optRawInput is set.


do, until


Executes a loop until the Arg given to until is true.


 [- $i = 0 -]
 [$ do $]
     [+ $i++ +] <BR>
 [$ until $i > 10 $]

foreach, endforeach


Executes a loop for each element of the second Arg, setting the first Arg accordingly.


 [- @arr = (1, 3, 5) -]
 [$ foreach $v @arr $]
     [+ $v +] <BR>
 [$ endforeach $]



Arg consists of zero, one or two names of hashes (with or without the leading %) and an optional array as third parameter. The hidden metacommand will generate hidden fields for all data contained in the first hash but not in the second hash. The default used for the first hash is %fdat, %idat is used for the second.

If the third parameter is specified, the fields are written in the order they appear in this array. That is, all keys of the first hash must be properly sorted in this array. This is intended for situations where you want to pass data from one form to the next, for example, two forms which should be filled in one after the other. (Examples might be an input form and a second form to review and accept the input, or a Windows-style "wizard"). Here you can pass along data from previous forms in hidden fields. (See eg/x/neu.htm for an example.) If you use just the 'hidden' command without parameters, it simply generates hidden fields for all form fields submitted to this document which aren't already contained in another input field.


    <FORM ACTION="inhalt.htm" METHOD="GET">
	<INPUT TYPE="TEXT" NAME="field1">
    [$ hidden $]

If you request this with http://host/doc.htm?field1=A&field2=B&field3=C

the output will be

    <FORM ACTION="inhalt.htm" METHOD="GET">

NOTE: This should only be used for a small amount of data, since the hidden fields are sent to the browser, which sends it back with the next request. If you have a large amount of data, store it in a file with a unique name and send only the filename in a hidden field. Be aware of the fact that the data can be changed by the browser if the user doesn't behave exactly as you expect. Users have a nasty habit of doing this all of the time. Your program should be able to handle such situations properly.




The var command declares one or more variables for use within this Embperl document and sets the strict pragma. The variable names must be supplied as a space-separated list.

Example: [$var $a %b @c $]

This is the same as writing the following in normal Perl code:

use strict ; use vars qw($a %b @c) ;

NOTE 1: `use strict' within an Embperl document will only apply to the block in which it occurs.




(Only Embperl 1.2b5 and above)

Defines a Embperl subroutine. Example:

  [$ sub foo $]
    <p> Here we do something </p>
  [$ endsub $]

You can call this subroutine either as a normal Perl subroutine

  [- foo -]

or via the HTML::Embperl::Execute function.

  [- Execute ('#foo')           # short form -]
  [- Execute ({ sub => 'foo'})  # long form  -]

The difference is that the Execute function will reset the internal states of Embperl like they were before the subrountine call, when the subroutine returns. Also Execute could handle recursive call, which currently not work when calling it as a Perl subroutine.

You may also pass Parameters to the subroutine:

  [$ sub foo $]
    [- $p = shift -]
    <p> Here we show the first parameter [+ $p +]</p>
  [$ endsub $]

  [- foo ('value') -]

If you have a couple of commonly used subroutines you can define then in one file and import them into the modules where they are neccesary:

  [- Execute ({ inputfile => 'mylib.htm', import => 1 }) -]

This will import all subroutines from the file mylib.htm into the current page where they could call just as a normal Perl subroutine.

HTML Tagstop

Embperl recognizes the following HTML tags in a special way. All others are simply passed through, as long as they are not part of a Embperl command.




Embperl can generate dynamic tables (one- or two-dimensional). You only need to specify one row or column.

Embperl generates as many rows or columns as necessary. This is done by using the magic variables $row, $col, and $cnt. If you don't use $row/$col/$cnt within a table, Embperl does nothing and simply passes the table through.

Embperl checks if any of $row, $col, or $cnt is used. Embperl repeats all text between <table> and </table>, as long as the expressions in which $row or $cnt occurs are defined.

Embperl repeats all text between <tr> and </tr>, as long as the expressions in which $col or $cnt occurs are defined.

See also $tabmode (below) for end-of-table criteria.

Examples: (see eg/x/table.htm for more examples)

 [- @k = keys %ENV -]
         <TD>[+ $i=$row +]</TD>
         <TD>[+ $k[$row] +]</TD>
         <TD>[+ $ENV{$k[$i]} +]</TD>

This will show all entries in array @k (which contains the keys from %ENV), so the whole environment is displayed (as in the while example), with the first column containing the zero-based index, the second containing the content of the variable name, and the third the environment variable's value.

This could be used to display the result of a database query if you have the result in an array. You may provide as many columns as you need. It is also possible to call a 'fetch' subroutine in each table row.




The <TH> tag is interpreted as a table heading. If the whole row is made up of <TH> </TH> instead of <TD> </TD>, it is treated as a column heading. Everything else will be treated as row headings in the future, but are not now: everything else is ignored in the current version.




Lists and dropdowns or list boxes are treated exactly as one- dimensional tables. Only $row, $maxrow, $col, $maxcol and $tabmode are honored. $col and $maxcol are ignored. See eg/x/lists.htm for an example.




Embperl checks if there is a value from the form data for a specific option in a menu. If so, this option will be pre-selected.


<FORM METHOD="POST"> <P>Select Tag</P>

  If you request this document with list.htm?SEL1=x
  you can specify that the element which has a value
  of x is initially selected

     <OPTION VALUE="[+ $v[$row] +]">
        [+ $k[$row] +]



The INPUT tag interacts with the hashes %idat and %fdat. If the input tag has no value and a key exists with the same text as the NAME attribute of the input tag, Embperl will generate a VALUE attribute with the corresponding value of the hash key. All values of <INPUT> tags are stored in the hash %idat, with NAME as the hash key and VALUE as the hash value. Special processing is done for TYPE=RADIO and TYPE=CHECKBOX. If the VALUE attribute contains the same text as the value of the hash the CHECKED attribute is inserted, else it is removed.

So, if you specify, as the ACTION URL, the file which contains the form itself, the form will be redisplayed with same values as entered the first time. (See eg/x/neu.htm for an example.)




The TEXTAREA tag is treated exactly like other input fields.




<meta http-equiv= ... > will over-ride the corresponding http header. This keeps Netscape from asking the user to reload the document when the content-type differs between the http header and the meta http-equiv.

This can also be used to set http headers. When running under mod_perl http-headers can also be set by the function header_out

    Example of how to set a http header:


    This is the same as using the Apache function

    [- $req_rec ->  header_out("Language" => "DE"); -]



The output of perl blocks inside the HREF attribute of the A Tags and the SRC attribute of the other Tags are URL escaped instead of HTML escaped. (see also $escmode). Also, when inside such a URL, Embperl expands array and hash references to URL parameter syntax. Example:

  $A = { A => 1, B => 2 } ;  # Hashreference
  @A = (X, 9, Y, 8, Z, 7)

  <A HREF="http://localhost/tests?[+ $A  +]">  
  <A HREF="http://localhost/tests?[+ \@A +]">

is expanded by Embperl to

  <A HREF="http://localhost/tests?A=1&amp;B=2">
  <A HREF="http://localhost/tests?X=9&amp;Y=8&Z=7">

[ << Prev: Runtime configuration ] [ Content ] [ Next: Variable scope and cleanup >> ]

© 1997-2012 Gerald Richter / ecos gmbh