This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: HTML/FormatTableRow, Next: HTML/FormatTableRowNroff, Prev: HTML/FormatTableNroff, Up: Module List Format HTML Table row ********************* NAME ==== HTML::FormatTableRow - Format HTML Table row SYNOPSIS ======== require HTML::FormatTableRow; @ISA = qw(HTML::FormatTableRow); DESCRIPTION =========== The HTML::FormatTableRow is used to record information and process a table row. This is a base class. The following attributes are supported: align: 'left','center', or 'right' alignment of table row entries valign: vertical alignment, 'top' or 'middle' METHODS ======= $table_row = new HTML::FormatTableRow(%attr); --------------------------------------------- The following attributes are supported: align: 'left','center', or 'right' alignment of table row entries valign: vertical alignment, 'top' or 'middle' $table_row->add_text($text); ---------------------------- Add text to cell. $table_row->text(); ------------------- Return text associated with current table cell. $table_row->widths($final, $array_ref); --------------------------------------- push the array of cell widths (in characters) onto the array specified using the array reference $array_ref. $table_row->output($final, $formatter, $tab); --------------------------------------------- Output the row data using the $formatter to do the output, and separating each cell using the $tab character. $final is not used. SEE ALSO ======== *Note HTML/FormatTable: HTML/FormatTable, COPYRIGHT ========= Copyright (c) 1997 Frederick Hirsch. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AUTHOR ====== Frederick Hirsch  File: pm.info, Node: HTML/FormatTableRowNroff, Next: HTML/FormatText, Prev: HTML/FormatTableRow, Up: Module List Format HTML Table row for nroff ******************************* NAME ==== HTML::FormatTableRowNroff - Format HTML Table row for nroff SYNOPSIS ======== require HTML::FormatTableRowNroff; $row = new HTML::FormatTableRowNroff(%attr); DESCRIPTION =========== The HTML::FormatTableRowNroff class is used to store information about a single row of a table. Once information about all the rows of the table has been recorded, an nroff tbl table may be created. The following attributes are supported: align: 'left','center', or 'right' alignment of table row entries valign: vertical alignment, 'top' or 'middle' METHODS ======= $nroff_row->output_format($last_row, $formatter, @widths); ---------------------------------------------------------- Create a tbl format line for the row. $last_row is true if this is the last row in the table. $formatter is the formatter being used (e.g. `HTML::FormatNroff'). @widths is an array of width information for each cell in the current row, specified in inches. $nroff_row->add_element(%attr); ------------------------------- Add a new cell to the current row. %attr are the cell attributes, as defined in `HTML::FormatTableCellNroff'. $nroff_row->end_element(); -------------------------- Finish the current cell. SEE ALSO ======== *Note HTML/FormatTable: HTML/FormatTable,, *Note HTML/FormatTableNroff: HTML/FormatTableNroff, *Note HTML/FormatTableRow: HTML/FormatTableRow, *Note HTML/FormatTableCell: HTML/FormatTableCell, *Note HTML/FormatTableCellNroff: HTML/FormatTableCellNroff, COPYRIGHT ========= Copyright (c) 1997 Frederick Hirsch. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AUTHOR ====== Frederick Hirsch  File: pm.info, Node: HTML/FormatText, Next: HTML/Formatter, Prev: HTML/FormatTableRowNroff, Up: Module List Format HTML as text ******************* NAME ==== HTML::FormatText - Format HTML as text SYNOPSIS ======== require HTML::TreeBuilder; $tree = HTML::TreeBuilder->new->parse_file("test.html"); require HTML::FormatText; $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 50); print $formatter->format($tree); DESCRIPTION =========== The HTML::FormatText is a formatter that outputs plain latin1 text. All character attributes (bold/italic/underline) are ignored. Formatting of HTML tables and forms is not implemented. You might specify the following parameters when constructing the formatter: leftmargin (alias *lm*) The column of the left margin. The default is 3. rightmargin (alias rm) The column of the right margin. The default is 72. SEE ALSO ======== *Note HTML/Formatter: HTML/Formatter, COPYRIGHT ========= Copyright (c) 1995-1999 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AUTHOR ====== Gisle Aas  File: pm.info, Node: HTML/Formatter, Next: HTML/FromText, Prev: HTML/FormatText, Up: Module List Base class for HTML formatters ****************************** NAME ==== HTML::Formatter - Base class for HTML formatters SYNOPSIS ======== package HTML::FormatXX; require HTML::Formatter; @ISA=qw(HTML::Formatter); DESCRIPTION =========== HTML formatters are able to format a HTML syntax tree into various printable formats. Different formatters produce output for different output media. Common for all formatters are that they will return the formatted output when the format() method is called. Format() takes a HTML::Element as parameter. SEE ALSO ======== *Note HTML/FormatText: HTML/FormatText,, *Note HTML/FormatPS: HTML/FormatPS,, *Note HTML/Element: HTML/Element, COPYRIGHT ========= Copyright (c) 1995-2000 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AUTHOR ====== Gisle Aas  File: pm.info, Node: HTML/FromText, Next: HTML/HeadParser, Prev: HTML/Formatter, Up: Module List mark up text as HTML ******************** NAME ==== HTML::FromText - mark up text as HTML SYNOPSIS ======== use HTML::FromText; print text2html($text, urls => 1, paras => 1, headings => 1); DESCRIPTION =========== The `text2html' function marks up plain text as HTML. By default it expands tabs and converts HTML metacharacters into the corresponding entities. More complicated transformations, such as splitting the text into paragraphs or marking up bulleted lists, can be carried out by setting the appropriate options. SUMMARY OF OPTIONS ================== These options always apply: metachars Convert HTML metacharacters to entity references urls Convert URLs to links email Convert email addresses to links bold Mark up words with *asterisks* in bold underline Mark up words with _underscores_ as underlined You can then choose to treat the text according to one of these options: pre Treat text as preformatted lines Treat text as line-oriented paras Treat text as paragraph-oriented (If more than one of these is specified, pre takes precedence over lines which takes precedence over paras.) The following option applies when the lines option is specified: spaces Preserve spaces from the original text The following options apply when the paras option is specified: blockparas Mark up indented paragraphs as block quote blockquotes Ditto, also preserve lines from original blockcode Ditto, also preserve spaces from original bullets Mark up bulleted paragraphs as unordered list headings Mark up headings numbers Mark up numbered paragraphs as ordered list tables Mark up tables title Mark up first paragraph as level 1 heading `text2html' will issue a warning if it is passed nonsensical options, for example headings but not paras. These warnings can be supressed by setting $HTML::FromText::QUIET to true. OPTIONS ======= blockparas blockquotes blockcode These options cause to `text2html' to spot paragraphs where every line begins with whitespace, and mark them up as block quotes. If more than one of these options is specified, blockparas takes precedence over blockcode, which takes precedence over blockquotes. All three options are ignored unless the paras option is also set. The blockparas option marks up the paragraph as a block quote with no other changes. For example, Turing wrote, I propose to consider the question, "Can machines think?" becomes

Turing wrote,

I propose to consider the question, "Can machines think?"
The blockquotes option preserves line breaks in the original text. For example, From "The Waste Land": Phlebas the Phoenecian, a fortnight dead, Forgot the cry of gulls, and the deep sea swell becomes

From "The Waste Land":

Phlebas the Phoenecian, a fortnight dead,
Forgot the cry of gulls, and the deep sea swell
The blockcode option preserves line breaks and spaces in the original text and renders the paragraph in a fixed-width font. For example: Here's how to output numbers with commas: sub commify { local $_ = shift; 1 while s/^(-?\d+)(\d{3})/$1,$2/; $_; } becomes

Here's how to output numbers with commas:

sub commify {
  local $_ = shift;
  1 while s/^(-?\d+)(\d{3})/$1,$2/;
  $_;
}
bold Words surrounded with asterisks are marked up in bold, so `*abc*' becomes `abc'. bullets Spots bulleted paragraphs (beginning with optional whitespace, an asterisk or hyphen, and whitespace) and marks them up as an unordered list. Bulleted paragraphs don't have to be separated by blank lines. For example, Shopping list: * apples * pears becomes

Shopping list:

  • apples

  • pears

This option is ignored unless the paras option is set. email Spots email addresses in the text and converts them to links. For example Mail me at web@perl.com. becomes Mail me at web@perl.com. headings Spots headings (paragraphs starting with numbers) and marks them up as headings of the appropriate level. For example, 1. Introduction 1.1 Background 1.1.1 Previous work 2. Conclusion becomes

1. Introduction

1.1 Background

1.1.1 Previous work

2. Conclusion

This option is ignored unless the paras option is set. lines Formats the text so as to preserve line breaks. For example, Line 1 Line 2 becomes Line 1
Line 2 If two or more of the options pre, lines and paras are set, then pre takes precedence over lines, which takes precedence over paras. metachars Converts HTML metacharacters into their corresponding entity references. Ampersand (`E) becomes `E, less than (`<') becomes `E, greater than (`>') becomes `E, and quote (") becomes `E. This option is 1 by default. numbers Spots numbered paragraphs (beginning with whitespace, digits, an optional period/parenthesis/bracket, and whitespace) and marks them up as an ordered list. Numbered paragraphs don't have to be separated by blank lines. For example, To do: 1. Write thesis 2. Submit it 3. Celebrate becomes

To do:

  1. Write thesis

  2. Submit it

  3. Celebrate

This option is ignored unless the paras option is set. paras Format the text into paragraphs. Paragraphs are separated by one or more blank lines. For example, Paragraph 1 Paragraph 2 becomes

Paragraph 1

Paragraph 2

If two or more of the options pre, lines and paras are set, then pre takes precedence over lines, which takes precedence over paras. pre Wrap the whole input in a `
' element.  For example,

          preformatted
          text

     becomes

          
preformatted
          text
If two or more of the options pre, lines and paras are set, then pre takes precedence over lines, which takes precedence over paras. spaces Preserves spaces throughout the text. For example, Line 1 Line 2 Line 3 becomes Line 1
 Line  2
  Line   3 This option is ignored unless the lines option is set. tables Spots tables and marks them up appropriately. Columns must be separated by two or more spaces (this prevents accidental incorrect recognition of a paragraph where interword spaces happen to line up). If there are two or more rows in a paragraph and all rows share the same set of (two or more) columns, the paragraph is assumed to be a table. For example -e File exists. -z File has zero size. -s File has nonzero size (returns size). becomes

-eFile exists.
-zFile has zero size.
-sFile has nonzero size (returns size).

`text2html' guesses for each column whether it is intended to be left, centre or right aligned. This option is ignored unless the paras option is set. title Formats the first paragraph of the text as a first-level heading. For example, Paragraph 1 Paragraph 2 becomes

Paragraph 1

Paragraph 2

This option is ignored unless the paras option is set. underline Words surrounded with underscores are marked up with underline, so `_abc_' becomes `abc'. urls Spots Uniform Resource Locators (URLs) in the text and converts them to links. For example See https://perl.com/. becomes See https://perl.com/. SEE ALSO ======== The `HTML::Entities' module (part of the LWP package) provides functions for encoding and decoding HTML entities. Tom Christiansen has a complete implementation of RFC 822 structured field bodies. See `http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz'. Seth Golub's `txt2html' utility does everything that `HTML::FromText' does, and a few things that it would like to do. See `http://www.thehouse.org/txt2html/'. RFC 822: "Standard for the Format of ARPA Internet Text Messages" describes the syntax of email addresses (the more esoteric features of structured field bodies, in particular quoted-strings, domain literals and comments, are not recognized by `HTML::FromText'). See `ftp://src.doc.ic.ac.uk/rfc/rfc822.txt'. RFC 1630: "Universal Resource Identifiers in WWW" lists the protocols that may appear in URLs. `HTML::FromText' also recognizes "https:", but ignores "file:" because experience suggests that it results in too many false positives. See `ftp://src.doc.ic.ac.uk/rfc/rfc1630.txt'. AUTHOR ====== Gareth Rees `'. COPYRIGHT ========= Copyright (c) 1999 Canon Research Centre Europe. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.  File: pm.info, Node: HTML/HeadParser, Next: HTML/INSTALL, Prev: HTML/FromText, Up: Module List Parse section of a HTML document *************************************** NAME ==== HTML::HeadParser - Parse section of a HTML document SYNOPSIS ======== require HTML::HeadParser; $p = HTML::HeadParser->new; $p->parse($text) and print "not finished"; $p->header('Title') # to access .... $p->header('Content-Base') # to access $p->header('Foo') # to access DESCRIPTION =========== The *HTML::HeadParser* is a specialized (and lightweight) HTML::Parser that will only parse the ... section of an HTML document. The parse() method will return a FALSE value as soon as some element or body text are found, and should not be called again after this. The *HTML::HeadParser* keeps a reference to a header object, and the parser will update this header object as the various elements of the section of the HTML document are recognized. The following header fields are affected: Content-Base: The *Content-Base* header is initialized from the element. Title: The Title header is initialized from the ... element. Isindex: The *Isindex* header will be added if there is a element in the . The header value is initialized from the prompt attribute if it is present. If no prompt attribute is given it will have '?' as the value. X-Meta-Foo: All elements will initialize headers with the prefix "`X-Meta-'" on the name. If the element contains a `http-equiv' attribute, then it will be honored as the header name. METHODS ======= The following methods (in addition to those provided by the superclass) are available: $hp = HTML::HeadParser->new( [$header] ) The object constructor. The optional $header argument should be a reference to an object that implement the header() and push_header() methods as defined by the *HTTP::Headers* class. Normally it will be of some class that isa or delegates to the *HTTP::Headers* class. If no $header is given *HTML::HeadParser* will create an *HTTP::Header* object by itself (initially empty). $hp->header; Returns a reference to the header object. $hp->header( $key ) Returns a header value. It is just a shorter way to write `$hp->header->header($key)'. EXAMPLE ======= $h = HTTP::Headers->new; $p = HTML::HeadParser->new($h); $p->parse(<Stupid example Normal text starts here. EOT undef $p; print $h->title; # should print "Stupid example" SEE ALSO ======== *Note HTML/Parser: HTML/Parser,, *Note HTTP/Headers: HTTP/Headers, The *HTTP::Headers* class is distributed as part of the *libwww-perl* package. COPYRIGHT ========= Copyright 1996-1999 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.  File: pm.info, Node: HTML/INSTALL, Next: HTML/Intro, Prev: HTML/HeadParser, Up: Module List INSTALLATION ============ UNIX ---- - *Unpack the archive* - *perl Makefile.PL* You will be asked if you want to compile in support for Apache mod_perl. If you say yes, the source of Apache is searched (for headerfiles). If it can't found, please specify the basepath. Please make sure mod_perl is already installed. If you have installed mod_perl-0.96 or higher, Makefile.PL automatically suggests the same source path as was used to build mod_perl. - make - make test - make install *NOTE 1:* (only Embperl-1.2b1 or higher) For using session handling you need Apache::Session-1.00 or higher. If possible use Apache::Session 1.52 or higher. Starting with Embperl 1.3b7 Apache::Session 0.17 is *NOT* supported anymore. *NOTE 2:* *Embperl* runs without additional Perl modules, but the make test needs the following modules to work: * URI * MIME::Base64 * HTML::Parser * HTML::HeadParser * Digest::MD5 * libnet * libwww * libwin32 (only Win32) *NOTE 3:* EmbperlObject needs the following modules to work: * File::Spec 0.82 or higher If you have already successfully build and tested mod_perl all modules will already be there. Options for make test --------------------- make test can take several options, with can be given with the `TESTARGS' parameter: make test TESTARGS="--help" will show you a list of available option. Most of them you will never need, they are mainly nesseccary for debugging *Embperl* itself. Debian packages --------------- The Debian packages are maintained by Angus Lees. Here are his installation hints: i've also setup an apt repository for those using stable (potato). to use it, just add these lines to /etc/apt/sources.list (deb-src line is only necessary if you want to download the source at some point): deb http://www.cse.unsw.edu.au/~gusl/embperl stable/binary-$(ARCH)/ deb-src http://www.cse.unsw.edu.au/~gusl/embperl stable/source/ then run "apt-get update" followed by either "apt-get install libhtml-embperl-perl" or just "apt-get upgrade" if you already have embperl installed. if you don't like apt, and want to do it the old fashioned way, i'm sure you can work out how to download the .deb manually. notes: currently i only have i386 packages built for stable. if anyone wants to build other archs and let me know, i can add them in (else, i can probably get a sparc and alpha version compiled) the package for unstable is compiled against perl5.6, so it has to conflict with earlier mod_perl packages that are compiled against perl5.5. unfortunately, there is no perl5.6 apache-perl package yet (drow assures me he's uploading one soon), so you have to make do with a DSO mod-perl (ie: apache + libapache-mod-perl) for now. WIN 32 ------ I have tested the offline mode on Windows 95 with a Microsoft Visual C++ 4.2 compiler and I have succesfully run Embperl with apache_1.3b5-1.3.9 / mod_perl-1.12-1.21 / perl5.004_04-perl5.005 (without threads) on Windows NT with VC++ 5.0. NOTE: It was necessary for me to compile perl5.004_04 with the VC++ on my own to get it to run with Apache and mod_perl, while I was able to use the binary distribution (/authors/id/GSAR/perl5.00402-bindist04-bc.tar.gz) of Perl for offline testing under Win 95. NOTE: You need mod_perl >= 1.12 on win32 On Windows 95/NT you have to do the following: *perl Makefile.PL* *nmake* (you must have the c compiler in your path) if you get an error about compiling Embperl.c. Edit Embperl.c and change -#line "Embperl.xs" to +#line 1 "Embperl.xs" now re-run nmake and it should compile. *nmake test* NOTE: nmake test needs libwin32, libwww and HTML::Parser installed to work *nmake install* *NOTE 1:* (only Embperl-1.2b1 or higher) For using session handling you need Apache::Session-1.00 or higher. If possible use Apache::Session 1.52 or higher. Starting with Embperl 1.3b7 Apache::Session 0.17 is *NOT* supported anymore. *NOTE 2:* *Embperl* runs without additional Perl modules, but the make test needs the following modules to work: * URI * MIME::Base64 * HTML::Parser * HTML::HeadParser * Digest::MD5 * libnet * libwww * libwin32 (only Win32) *NOTE 3:* EmbperlObject needs the following modules to work: * File::Spec 0.82 or higher If you have already successfully build and tested mod_perl all modules will already be there. Further Documentation (english) ------------------------------- See `"perldoc Features"|"Features.pod"' in this node for list of Embperls features See `"perldoc Intro"|"Intro.pod"' in this node for an step by step introduction to Embperl. See `"perldoc IntroEmbperlObject"|"IntroEmbperlObject.pod"' in this node for an step by step introduction to the OO features of Embperl. See `"perldoc Embperl"|"Embperl.pod"' in this node for complete documentation. See the `"eg' in this node directory for examples. See `"perldoc Faq"|"Faq.pod"' in this node for Frequently Asked Questions. See `"perldoc TipsAndTricks"|"TipsAndTricks.pod"' in this node for Tips and Tricks around Embperl. or you can view it online on http://perl.apache.org/embperl/ Further Documentation (german) ------------------------------ See *perldoc FeaturesD* for list of Embperls features See *perldoc IntroD* for an step by step introduction to Embperl. See *perldoc EmbperlD* for complete documentation. or you can view it online on http://www.ecos.de/embperl/  File: pm.info, Node: HTML/Intro, Next: HTML/IntroD, Prev: HTML/INSTALL, Up: Module List Content ======= What is Embperl? Embed Perl Code in HTML Documents Meta-Commands Dynamic Tables Form Processing Maintaining persistent (session) data Breaking up your code in components Debugging Database Access Security Escaping/Unescaping What is Embperl? ================ Embed Perl Code in HTML Documents --------------------------------- The main purpose of HTML::Embperl is to embed Perl code in HTML documents. While Embperl can also be used with non-HTML documents, it has several features that are specifically for HTML. How does it compare to ASP, PHP, ePerl? --------------------------------------- Embperl is not the only processor for embedded Perl code. ASP used with ActiveState Perl port provides this for Microsoft IIS, and ePerl is a solution which does this job very well for all sorts of ASCII files. There are other Perl solutions around as well. PHP is a well-known solution for easily building web pages with embedded code and database connections, but it's not Perl. Additional HTML features ------------------------ The main advantage of Embperl is the built-in HTML awareness. It provides features for handling form data and HTML tables, along with converting log files and error pages to HTML and linking them together. It also allows for escaping and unescaping. Integration with Apache and mod_perl ------------------------------------ Embperl can be used offline (as a normal CGI script or as a module from other Perl code), but its real power comes when running under mod_perl and Apache. It's directly integrated with Apache and mod_perl to achieve the best performance by directly using Apache functions and precompiling your code to avoid a recompile on every request. For Usage With High Level HTML Editor ------------------------------------- Embperl was designed to be used with a high-level HTML editor. The Perl code can be entered as normal text (the editor need not know any special HTML tags nor is it necessary to enter special HTML tags via uncomfortable dialogs); just enter your code as if it were normal text. Embperl takes care of unescaping the HTML codes and eliminates unwanted HTML tags (like
) which are entered into your Perl code by the editor (e.g. because you like to have a line break for better readability). How to Embed Perl Code in HTML Documents ======================================== Perl code can be embedded in three ways: 1.) [- ... -] Execute code -------------------------------- [- $a = 5 -] [- $b = 6 if ($a == 5) -] The code between the [- and the -] is executed. No output will be generated. This is mainly for assignments, function calls, database queries, etc. 2.) [+ ... +]Output the result --------------------------------- [+ $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). 3.) [! ... !] Execute code once ------------------------------------- [! 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-Commands ------------- 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: [$ $] 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 +]
[$ 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 ... ..................... 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. Dynamic Tables ============== A very powerful feature of Embperl is the processing of dynamic tables. This feature was designed mainly to display Perl arrays (one or two dimensional, regular and irregular), but can also be used in other ways. Display a Perl Array -------------------- [- @a = ( 'A', 'B', 'C') ; -]
[+ $a[$row] +]
The above example simply displays a table with three rows containing A, B and C. The trick is done by using the magical variable $row which contains the row count and is incremented for every row. The table ends if the expression which contains $row returns . The same can be done with $col for columns and $cnt can be used if you need a table which wraps after a certain number of elements. This works with table/select/menu/ol/dl/dir Simple DBI Example ------------------ Here is a simple DBI example that displays the result of a query as a two dimension table, with field names as headings in the first row: [- # connect to database $dbh = DBI->connect($DSN) ; # prepare the sql select $sth = $dbh -> prepare ("SELECT * from $table") ; # excute the query $sth -> execute ; # get the fieldnames for the heading in $head $head = $sth -> {NAME} ; #continues on the next page... # get the result in $dat $dat = $sth -> fetchall_arrayref ; -]
[+ $head->[$col] +]
[+ $dat -> [$row][$col] +]
Form fields =========== Posted form data available in %fdat/@ffld ----------------------------------------- The hash %fdat contains all values of form fields. The array @ffld contains the names in the order in which they were submitted. Input/Textarea/Select tags take values from %fdat ------------------------------------------------- If you do not specify a default value for an input tag and a value for that input tag is available in %fdat, Embperl will automatically insert this value and send it to the browser. This is similar to the behavior of CGI.pm. This means that if you post a form to itself, the browser will display the values you just entered. [$ hidden $] ------------ [$ hidden $] creates hidden form fields for all fields not in another input field. This can be used to transport data through confirmation forms. (For example, a wizard.) A simple Text input / Confirmation form --------------------------------------- The following example shows many of the possibilities of Embperl. It's a simple form where you can enter your name, your email address and a message. If you hit the send button, you see the data you just entered and can confirm the information by hitting the "send via mail" button, or you can go back to the input form to change the data. If you confirm your input, the data will be sent to a predefined e-mail address. The example also shows how you can implement error checking-if you miss your name or your e- mail address, you will get a corresponding error message and the input form is shown again. The first part is the error checking; the second part the confirmation form; the third part sends the mail if the input was ok and is confirmed; the last part is the input form itself. Depending on the values of $fdat{check}, $fdat{send} and if $fdat{name} and $fdat{email} contains data, the document decides which part to show. [- $MailTo = 'richter\@ecos.de' ; @errors = () ; if (defined($fdat{check}) || defined($fdat{send})) { push @errors, "**Please enter your name" if (!$fdat{name}) ; push @errors, "**Please enter your e-mail address" if (!$fdat{email}) ; } -] [$if (defined($fdat{check}) and $#errors == -1)$] [- delete $fdat{input} ; delete $fdat{check} ; delete $fdat{send} -]

You have entered the following data:

Name[+$fdat{name}+]
E-Mail[+$fdat{email}+]
Message[+$fdat{msg}+]
[$hidden$]
[$elsif defined($fdat{send}) and $#errors == -1$] [- MailFormTo ($MailTo,'Formdata','email') -]

Your input has been sent

[$else$]

Please enter your data

[$if $#errors != -1 $] [$endif$]
[+$errors[$row]+]
Name
E-Mail
Message
[$endif$] Maintaining persistent (session) data ===================================== (Embperl 1.2 or above) While hidden fields are useful when working with forms, it's often necessary to *store persistent data* in a more general way. Embperl utilizes *Apache::Session* to do this job. Apache::Session is caple of storing persistent data in memory, in a textfile or in a database. More storage methods may supported in the future. While you can simply call Apache::Session from an Embperl page, Embperl can do it for you. All you need to do is to put your data in the hash *%udat*. The next time the same user requests any Embperl page %udat will contain the same data. You can simply use this to keep state information for the user. Depending on your expire settings, the state can also kept between mulitiple sessions. A second hash, *%mdat*, can be used to keep a state for one page, but for multiple users. A simple example would be a page hit counter: The page is requested [+ $mdat{counter}++ +] times since [+ $mdat{date} ||= localtime +] The above example counts the page hits and shows the date when the page is first requested. You don't need to worry about performance - as long as you don't touch %udat or %mdat, no action is taken. Breaking your code up into components ===================================== (Embperl 1.2 or above) Subroutines ----------- It is better to write subroutines than to keep placing repetetive pieces of code in your program many times. You can do this with Embperl too. As an example, if you have text input fields with labels, this may work better for you: [$ sub textinput $] [- ($label, $name) = @_ -] [+ $label +] [$ endsub $]
[- textinput ('Last Name', 'lname') -]

[- textinput ('First Name', 'fname') -]

The sub metacommand starts the subroutine and the parameters are passed in the array `@_'. You can do anything in the subroutine that you would normally be able to do inside normal Embperl pages. Embperl lets you call this subroutine just like any other Perl subroutine: just write its name and, if necessary, the parameter list. Execute ------- If you are working on an entire site rather than just a few pages, you are well aware that there are always elements which occur in every page or across many pages. Instead of copying the source code to every page, you can include other Embperl pages in your page - so you have to write the source only once. Such an included page could be a header, a footer, a navigation bar, and so on. Embperl is not only capable of including such partial pages, you can also pass arguments - for example, to tell the navigation bar which of its own element to highlight: Example for a simple navigation bar [- @buttons = ('Index', 'Infos', 'Search') -]
[$if $buttons[$col] eq $param[0]$] [$endif$] [+ $buttons[$col] +] [$if $buttons[$col] eq $param[0]$] [$endif$]

Now if you are on the "Info" page you can include the navigation bar this way: [- Execute ('navbar.html', 'Infos') -] This will include the navigation bar, which is stored in the file navbar.html, and pass as its first parameter the string 'Infos'. The navigation bar module itself uses a dynamic table to display one column - which contains the text and a link - for every item in the array @buttons. The text which matches that which is passed as the first parameter is displayed in bold. There is also a long form of the Execute call, which allows you to control all of the details of how the called page is executed. Creating Component Libraries ---------------------------- Instead of creating a single file for every piece of HTML-code you wish to include, you can pack them together in just one library. To do this, split up every piece of code you want to include separately in one Embperl subroutine (sub-metacommand). Now, you can use the import parameter of the Execute function to import all of the subrountines defined in one file, into the namespace of the current page. Afterwards, you are able to call them just like any other Perl subroutine. Moreover, if you wish to have some systemwide Embperl subroutines, you can put all the Embperl code in a normal Perl module (a foo.pm file), install it into your Perl system (or a private library path), and use it just like any other Perl module - just by saying use mymodule; Debugging ========= Embperl log file ---------------- The log file is the main source for debugging. It shows you what Embperl does while it processes your page. Depending on the debug flag settings, Embperl logs the following things: Source Environment Form data Evals (Source + Result) Table processing Input tag processing HTTP headers Embperl log file can be viewed via the browser ---------------------------------------------- For debugging, you can tell Embperl to display a link at the top of each page to your log file. If you follow the link, Embperl will show the portion of the log file corresponding to that request. The log file lines are displayed in different colors to give a better overview. Embperl error page contains links to the log file ------------------------------------------------- If you have enabled links to the log file, every error displayed in an error page is a link to the corresponding position in the logfile, so you can easily find the place where something is going wrong. Database access =============== Plain DBI --------- This is another example of using plain DBI within Embperl. In opposition to the `example|"Simple DBI Example"' in this node I gave in the chapter about dynamic tables, this example works with explicit loops. [- # connect to database $dbh = DBI->connect($DSN) ; # prepare the sql select $sth = $dbh -> prepare ("SELECT * from $table") ; # excute the query $sth -> execute ; # get the fieldnames for the heading in $head $head = $sth -> {NAME} ; -] [$ foreach $h @$head $] [$ endforeach $] [$ while $dat = $sth -> fetchrow_arrayref $] [$ foreach $v @$dat $] [$ endforeach $] [$ endwhile $]
[+ $h +]
[+ $v +]
DBIx::Recordset --------------- DBIx::Recordset is a module for easy database access. Search Example -------------- [-*set = DBIx::Recordset -> Search ({%fdat, ('!DataSource' => $DSN, '!Table' => $table, '$max' => 5,)}) ; -]
IDNAME
[+ $set[$row]{id} +] [+ $set[$row]{name} +]
[+ $set -> PrevNextForm ('Previous Records', 'Next Records', \%fdat) +] Search sets up a Recordset object --------------------------------- Search will take the values from %fdat and use them to build a SQL WHERE expression. This way, what you search for depends on what is posted to the document. For example, if you request the document with http://host/mydoc.html?id=5 the above example will display all database records where the field 'id' contains the value 5. =head2 Data can accessed as array or via the current record The result of the query can be accessed as an array (this does not mean that the whole array is actually fetched from the database). Alternative, you can directly access the current record just by accessing the fields. set[5]{id} access the field 'id' of the sixth found record set{id} access the field 'id' of the current record Fields can be accessed by name ------------------------------ While normal DBI let you access your data by column numbers, DBIx::Recordset uses the field names. This makes your program easier to write, more verbose and independent of database changes. PrevNextForm generates no/one/two buttons depending if there are more records to display ---------------------------------------------------------------------------------------- The PrevNextButtons function can be used to generate button for showing the previous record or the next records. PrevNextButton generates a small form and includes all necessary data as hidden fields. To get it to work, it's enough to feed this data to the next request to Search. As for Search there are methods for Insert/Update/Delete -------------------------------------------------------- Example for Insert If %fdat contains the data for the new record, the following code will insert a new record into the database. [-*set = DBIx::Recordset -> Insert ({%fdat, ('!DataSource' => $DSN, '!Table' => $table)}) ; -] Database table can also tied to a hash -------------------------------------- DBIx::Recordset can also tie a database table to a hash. You need to specify a primary key for the table, which is used as key in the hash. $set{5}{name} access the name with the id=5 (id is primary key) Security ======== When running under mod_perl, all Perl code shares the same interpreter. This means that every application can access data from every other application. Embperl maintains a separate namespace for every document, which is enough to avoid accidentally overwriting other applications data, but there is no real security. You can access anything you like if you explicitly specify a package name. Safe namespaces --------------- Therefore, Embperl incorporates Safe.pm, which will make it impossible to access any packages other than your own. This can be used, for example, to calculate something in a Perl module and then pass the results to an Embperl document. If the Embperl document runs in a safe namespace, it can access the data it has received from the browser, but can't access outside itself. Therefore, it's safe to let different people create the layouts for Embperl pages. Operator restrictions --------------------- Safe.pm also permits the administrator to disable every Perl opcode. If you use this, you are able to decide which Perl opcodes are permitted to be used by the page creators. Escaping/Unescaping =================== Input: unescaping ----------------- (disable via optRawInput) - convert HTML escapes to characters (e.g. < to <) - remove HTML tags from Perl code (e.g.
insert by high level editor) Output: escaping ---------------- (disable via escmode) convert special characters to HTML (e.g. < to <)  File: pm.info, Node: HTML/IntroD, Next: HTML/LinkExtor, Prev: HTML/Intro, Up: Module List Content ======= Was ist Embperl? Perl Code in HTML Dokumente einfügen Meta-Commands Dynamische Tabellen Formularfelder Persistente Daten (Sessions) Aufteilen des Codes in mehrere Komponenten Debugging Datenbankzugriff Sicherheit Escaping/Unescaping Was ist Embperl? ================ Perl Code in HTML Dokumente einfügen ------------------------------------ Die Hauptanwendung von HTML::Embperl ist Perlcode in HTML Dokumente einzufügen. Embperl kann zwar ebenfalls mit nicht HTML Dokumenten benutzt werden, hat jedoch einige Features speziell für HTML. Zusätzliche HTML Features ------------------------- Einer der Vorteile von Embperl ist, daß es speziell auf HTML zugeschnitten ist. Es stellt u.a. Funktionen zur Formularbehandlung und für HTML Tabellen zur Verfügung, einhergehend mit der Fähigkeit Logdateien und Fehlerseiten in HTML darzustellen. Ebenso erledigt es die HTML und URL Kodierung. Dies verhindet jedoch nicht das Embperl mit allen Arten von Textdateien umgehen kann. Integration mit Apache und mod_perl ----------------------------------- Embperl kann offline (als normales CGI Skript oder als Modul dessen Funktionen sich von anderem Perlprogrammen/-modulen aufrufen lassen) benutzt werden, aber die meisten Möglichkeiten und beste Performance entwickelt es unter mod_perl und Apache. Dort werden direkt die Funktionen der Apache API genutzt und mod_perl erlaubt es den Code vorzukompilieren, um dadurch den Compilierungsvorgang bei jedem weiterem Request einzusparen. Embperl arbeitet mit HTML Editoren ---------------------------------- Embperl ist entworfen worden um direkt mit dem von HTML Editoren erzeugten Code zu arbeiten. Der Perlcode wird dabei als normaler Text eingeben. Es ist nicht nötig, das der HTML Editor spezielle HTML Tags kennt, noch müssen diese über umständliche Dialoge eingegeben werden. Embperl kümmert sich darum, z.B. ein vom HTML Editor erzeugtes < in < umzuwandeln, bevor es dem Perlinterpreter übergeben wird. Außerdem entfernt es unerwünschte HTML Tags, z.B. ein
, das der Editor eingefügt hat, weil man eine neue Zeile anfängt, aus dem Perlcode. Perl Code in HTML Dokumente einfügen ==================================== Perlcode kann auf drei Arten eingebettet werden: 1.) [- ... -] Führt den Code aus -------------------------------------- [- $a = 5 -] [- $b = 6 if ($a == 5) -] Der Code zwischen [- und -] wird ausgeführt, dabei wird keine Ausgabe erzeugt. Diese Form eignet sich für Zuweisungen, Funktionsaufrufe, Datenbankanfrage, usw. 2.) [+ ... +] Das Ergebnis ausgeben -------------------------------------- [+ $a +] [+ $array[$b] +] [+ "A is $a" +] Der Code zwischen dem [+ und dem +] wird ausgeführt und der Rückgabewert (der Wert des letzten Perlausdruckes welcher berechnet wurde) wird ausgegeben (zum Browser gesandt) 3.) [! ... !] Code nur einmal ausführen --------------------------------------------- [! sub foo { my ($a, $b) = @_ ; $a * $b + 7 } !] Genauso wie [- ... -], der Code wird jedoch nur einmal, für den ersten Request, ausgeführt. Dies ist hauptsächlich für Funktionsdefinitionen und einmalige Initialisierungen. Meta-Commands ============= Embperl unterstützt einige Meta-Commands um dem "Programmablauf" innerhalb des Embperldokuments zu steuern. Dies kann mit einem Preprozessor in C verglichen werden. Die Meta-Commands haben folgende Form: [$ $] if, elsif, else, endif ...................... Der if Befehl hat die selben Auswirkungen wie in Perl. Er kann genutzt werden um Teile des Dokuments nur unter bestimmten Bedingungen auszugeben/auszuführen. Beispiel: [$ if $ENV{REQUEST_METHOD} eq 'GET' $]

Dies ist ein GET Request

[$ elsif $ENV{REQUEST_METHOD} eq 'POST' $]

Dies ist ein POST Request

[$ else $]

Dies ist weder ein GET noch ein POST Request

[$ endif $] Dieses Beispiel gibt eine der drei Absätze in Abhänigkeit von dem Wert von $ENV{REQUEST_METHOD} aus. while, endwhile ............... Der while Befehl wird dazu benutzt, um eine Schleife innerhalb des HTML Dokuments zu erzeugen. Beispiel: [$ while ($k, $v) = each (%ENV) $] [+ $k +] = [+ $v +]
[$ endwhile $] Das Beispiel zeigt alle Environementvariablen, jede abgeschlossen mit einem Zeilenumbruch (
). do, until ......... do `until' erzeugt ebenso eine Schleife, jedoch mit der Bedingung am Ende. Beispiel: [- @arr = (3, 5, 7); $i = 0 -] [$ do $] [+ $arr[ $i++ ] +] [$ until $i > $#arr $] foreach, endforeach ................... Erzeugt eine Schleife, die über jedes Element einer Liste/Arrays iteriert. Beispiel: [$ foreach $v (1..10) $] [+ $v +] [$ endforeach $] var ... ..................... Standartmäßig ist es nicht nötig irgenwelche Variablen innerhalb einer Embperlseite zu deklarieren. Embperl kümmert sich darum nach jedem Request wieder aufzuräumen. Manchmal möchte man jedoch die zu benutzenden Variablen explizit deklarieren. Dies ist mit var möglich: [$ var $a @b %c $] Hat den selben Effekt wie der Perlcode: use strict ; use vars qw {$a @b %c} ; hidden ...... hidden ermöglicht es versteckte Formularfelder zu erzeugen und wird weiter unten im Abschnitt über Formularfelder beschrieben. Dynamische Tabellen =================== Ein sehr leistungsfähiges Feature von Embperl ist das Erzeugen von dynamischen Tabellen. Am einfachsten lassen sich auf diesem Weg Perlarrays in Tabellen umwandeln (ein- oder zweidimensional, gleich- und ungleichmäßige), aber auch andere Datenquellen sind möglich. Anzeigen eines Perlarrays ------------------------- [- @a = ( 'A', 'B', 'C') ; -]
[+ $a[$row] +]
Das obige Beispiel gibt einfach eine Tabelle mit drei Zeilen, welche A, B und C enthalten aus. Der Trick dabei ist die Benutzung der magischen Variable *$row*, welche die Zeilennummer innerhalb der Tabelle enthält und automatisch für jede Zeile um eins erhöht wird. Die Tabelle ist zu Ende, wenn der Block, in dem *$row* auftaucht, undef zurückgibt. Das funktioniert auch mit *$col* für Spalten und *$cnt* kann benutzt werden, wenn die Elemente, nach einer bestimmten Anzahl, in die nächste Reihe rutschen sollen. Dies funktioniert ebenso mit table/select/menu/`ol'/`dl'/dir Einfaches DBI Beispiel ---------------------- Hier ist ein einfaches DBI Beispiel, welches das Ergebnis einer Anfrage in einer zwei dimensionalen Tabelle anzeigt, mit den Feldnamen als Überschrift in der ersten Zeile: [- # Verbinden mit Datenbank $dbh = DBI->connect($DSN) ; # SQL Select vorbereiten $sth = $dbh -> prepare ("SELECT * from $table") ; # Datenbankanfrage ausführen $sth -> execute ; # $head erhält die Feldnamen für die Tabellenüberschrift $head = $sth -> {NAME} ; # $dat erhält die Datensätze $dat = $sth -> fetchall_arrayref ; -]
[+ $head->[$col] +]
[+ $dat -> [$row][$col] +]
Formularfelder ============== Gesendete Formulardaten sind in %fdat/@ffld verfügbar ----------------------------------------------------- Der Hash *%fdat* enthält alle Werte der Formularfelder. Das Array *@**ffld* enthält die Namen in der Reihenfolge wie sie gesendet wurden. Input/Textarea/Select tags erhalten ihre Werte aus %fdat -------------------------------------------------------- Wenn innerhalb des HTML Codes kein Wert für ein Inputtag angegeben ist und Daten in *%fdat* dafür verfügbar sind, fügt Embperl automatisch den Wert aus *%fdat* ein. Dies ist ähnlich dem Verhalten von CGI.pm. Das bedeutet, daß wenn man die Daten eines Formular (in einer Embperlseite) an sich selbst schickt, automatisch die Daten wieder angezeigt werden, die gerade eingegeben wurden. [$ hidden $] ------------ [$ hidden $] erzeugt versteckte Formularfelder für alle Werte aus *%fdat*, die bis dahin nicht in einem anderem Formularfeld ausgegeben wurden. Dies ist hilfreich, wenn Daten über mehere Formulare hinweg transportiert werden müssen. Ein einfaches Texteingabe/Bestätigungs Formular ----------------------------------------------- Das folgende Beispiel zeigt viele der Möglichkeiten von Embperl. Es ist ein einfaches Formular, in dem man seinen Namen, seine Email Adresse, sowie eine Nachricht eingeben kann. Wenn man es absendet, werden die Daten zunächst noch einmal angezeigt. Von dort kann man zum vorherigen Formular zurückkehren, um die Daten zu korrigieren oder der Benutzer bestätigt die Daten, wodurch sie zu einer vordefinierten Email Adresse gesandt werden. Das Beispiel zeigt auch wie eine Fehlerüberprüfung implementiert werden kann. Wenn der Name oder die Email Adresse weggelassen wird, wird eine entsprechende Fehlermeldung angezeigt und das Eingabeformular erscheint wieder. Der erste Teil ist die Fehlerüberprüfung; der zweite Teil die Bestätigungsseite; der dritte Teil versendet die Email, wenn die Eingaben bestätigt wurden und der letzte Teil ist das Eingabeformular. In Abhängigkeit der Werte von `$fdat{check}', `$fdat{send}' und ob `$fdat{name}' und `$fdat{email}' Daten enthalten, entscheidet das Dokument welcher Teil zur Ausführung kommt. [- $MailTo = 'richter\@ecos.de' ; @errors = () ; if (defined($fdat{check}) || defined($fdat{send})) { push @errors, "**Bitte Namen eingeben" if (!$fdat{name}) ; push @errors, "**Bitte E-Mail Adresse eingeben" if (!$fdat{email}) ; } -] [$if (defined($fdat{check}) and $#errors == -1)$] [- delete $fdat{input} ; delete $fdat{check} ; delete $fdat{send} -]

Sie haben folgende Daten eingegeben:

Name[+$fdat{name}+]
E-Mail[+$fdat{email}+]
Nachricht[+$fdat{msg}+]
[$hidden$]
[$elsif defined($fdat{send}) and $#errors == -1$] [- MailFormTo ($MailTo,'Formdata','email') -]

Ihre Nachricht wurde abgeschickt

[$else$]

Bitte geben Sie Ihre Daten ein

[$if $#errors != -1 $] [$endif$]
[+$errors[$row]+]
Name
E-Mail
Nachricht
[$endif$] Persistente Daten (Sessions) ============================ (Embperl 1.2 oder neuer) Während versteckte Felder gut innerhalb Formularen einsetzbar sind, ist es oft notwendig *Daten persistent* auf eine allgemeinere Art und Weise zu speichern. Embperl benutzt *Apache::Session* um dies durchzuführen. *Apache::Session* ermöglicht die Daten im Speicher, in einem Textfile oder in einer Datenbank abzuspeichern. Weitere Speichermöglichkeiten sind für die Zukunft zu erwarten. Man kann zwar einfach *Apache::Session* aus Embperl Seiten herausaufrufen, aber Embperl ist in der Lage dies für den Benutzer transparent durchzuführen. Es genügt einfach seine Daten in dem Hash *%udat* abzuspeichern, sobald der selbe Benutzer wieder eine Embperl Seite aufruft, stehen in %udat wieder die selben Daten. Dies ermöglicht auf eine einfache Art und Weise Zustandsinformationen für einen Benutzer zu speichern. In Abhängigkeit vom Ablaufzeitpunkt können so Benutzerspezifische Daten auch über einen längeren Zeitraum hinweg gespeichert werden. Ein zweiter Hash, *%mdat*, dient dazu, Daten, die zu einer bestimmten Seite gehören, zu speichern. Ein einfaches Beispiel ist z.B. ein Zähler der Anzahl der Seitenaufrufe: Die Seite wurde seit dem [+ $mdat{date} ||= localtime +] [+ $mdat{counter}++ +] mal abgerufen Das obige Beispiel zählt die Anzahl der Abrufe und zeigt die Zeit, wann die Seite zum ersten Mal aufgerufen wurde. Embperl sorgt dafür, dass die Daten nur dann wieder abgespeichert werden, wenn sie auch geändert wurden. Aufteilen des Codes in mehrere Komponenten ========================================== (Embperl 1.2 oder neuer) Funktionen ---------- Wächst ein Programm, teilt man es in mehere Funktionen auf. Dies ist mit Embperlseiten ebenfalls möglich. Folgendes Beispiel zeigt dies an Hand von beschrifteten Texteingabefeldern: [$ sub textinput $] [- ($label, $name) = @_ -] [+ $label +] [$ endsub $]
[- textinput ('Nachname', 'lname') -]

[- textinput ('Vorname', 'fname') -]

Das sub Meta-Command kennzeichnet den Anfang der Funktion und die Parameter werden im Array `@_' übergeben. Man kann innerhalb der Funktion alles tun, was auch in einer normalen *Embperl* Seite möglich ist. Aufgerufen wird die Funktion, wie jede andere Perlfunktion auch, einfach durch Schreiben des Namens und ggf. der Parameterliste. Execute ------- Wenn man an einer ganzen Website arbeitet, kommt es meistens vor, daß es Elemente gibt, die in jeder oder vielen Seiten immer wieder vorkommen. Anstatt den Quellencode nun in jede Seite zu kopieren, ist es möglich *Embperl Module* in die Seite einzufügen, so daß der Quellencode nur einmal existieren muß. So ein Modul könnte z.B. ein Kopf, ein Fuß, eine Navigationsleiste usw. sein. Es können dabei nicht nur Teile einer Seite eingefügt, sondern auch, ähnlich einem Unterprogramm, Argumente übergeben werden - z.B. um der Navigationsleiste mitzuteilen, welches Element hervorzuheben ist. Beispiel für eine einfache Navigationsleiste [- @buttons = ('Index', 'Infos', 'Suchen') -]
[$if $buttons[$col] eq $param[0]$] [$endif$] [+ $buttons[$col] +] [$if $buttons[$col] eq $param[0]$] [$endif$]

Wenn man nun auf der Info-Seite ist, kann die Navigationsleiste wie folgt eingefügt werden: [- Execute ('navbar.html', 'Infos') -] Dies fügt die Navigationsleiste, welche in der Datei navbar.html gespeichert ist, an entsprechender Stelle ein und übergibt ihr als Parameter die Zeichenkette 'Infos'. Das Navigationsleistenmodul selbst benutzt eine dynamische Tabelle um die Spalten anzuzeigen, welche den Text und einen entsprechenden Link enthalten. Die Texte werden dabei dem Array @buttons entnommen. Wenn der Text gleich dem übergebenen Parameter ist, wird er fett dargestellt. Weiterhin gibt es noch eine ausführliche Form des Executeaufrufes, welche es erlaubt sehr detailiert die Ausführung des Moduls zu kontrollieren. Erstellen von Komponenten Libraries ----------------------------------- Statt eine extra Datei für jedes bischen HTML Code zu erstellen, welches in eine andere Seite eingefügt werden soll, ist es möglich diesen in eine HTML Datei zusammenzufassen. Um dies zuerreichen muß jedes einzelne Codestück eine eigene *Embperl* Funktion sein. Mittels des import Parameters der Execute Funktion können nun alle *Embperl* Funktionen in den Namensraum der aktuellen Seite importiert werden und fortan wie normale Perlfunktionen aufgerufen werden. Weiterhin ist es möglich die *Embperl* Funktionen (zusammen mit normalen Perl Code) als ein Perl Modul (.pm Datei) zu installieren. Dadurch stehen sie systemweit zur Verfügung und können wie jedes andere Perl Modul mittels use genutzt werden. EmbperlObject ============= (ab Embperl 1.3) Einen Schritt weiter als das einfache Einbetten von anderen Dateien mittels Execute geht EmbperlObject. EmbperlObject ist ein mod_perl handler, der es erlaubt eine Website in konsistenter Weise aus einzelnen Komponenten zusammenzusetzen. Dabei definiert man ein Rahmenlayout, welches "Platzhalter" für einzelne Elemente der Site (z.B. Kopf, Fuß, Navigation etc.) enthält. Diese "Platzhalter" können nun für unterschiedliche Bereiche (Unterverzeichnisse) der Site mit verschiedenen Inhalten gefüllt werden. Definiert ein Bereich (Unterverzeichnis) keinen eigenen Inhalt, wird automatisch der Inhalt des übergeordneten Verzeichnisses eingefügt. Konkret heißt das, man identifiziert Bereiche, die auf allen/vielen Seiten gleich aussehen sollen, macht daraus eine eigenständige Komponente (HTML Datei) und fügt diese dann nur noch an passender Stelle ein. Es leuchtet ein, dass dies das Design und Änderungen wesentlich vereinfacht, da eine Änderung in der Komponente sich auf alle Seiten auswirkt. Hier ein einfaches Beispiel, um zu verdeutlichen wie EmbperlObject arbeitet; dabei definert base.htm das Rahmenlayout, head.htm enthält den Kopf und foot.htm den Fuß für die Seite: *Anordnung der Dateien:* /foo/base.htm /foo/head.htm /foo/foot.htm /foo/page1.htm /foo/sub/head.htm /foo/sub/page2.htm */foo/base.htm:* Beispiel [- Execute ('head.htm') -] [- Execute ('*') -] [- Execute ('foot.htm') -] */foo/head.htm:*

Kopf aus foo

*/foo/sub/head.htm:*

Hier ein anderer Kopf aus dem Verzeichnis sub

*/foo/foot.htm:*
Fußzeile
*/foo/page1.htm:* Hier steht der Inhalt von Seite 1 */foo/sub/page2.htm:* Hier steht der Inhalt von Seite 2 */foo/sub/index.htm:* Index im Verzeichnis /foo/sub Der Request *http://host/foo/page1.htm* führt dann zu folgender Seite: Beispiel

Kopf aus foo

Hier steht der Inhalt von Seite 1
Fußzeile
Der Request *http://host/foo/sub/page2.htm* führt dann zu folgender Seite: Beispiel

Hier ein anderer Kopf aus dem Verzeichnis sub

Hier steht der Inhalt von Seite 2
Fußzeile
Der Request *http://host/foo/sub/* führt dann zu folgender Seite: Beispiel

Hier ein anderer Kopf aus dem Verzeichnis sub

Index im Verzeichnis /foo/sub
Fußzeile
Debugging ========= Embperl Logdatei ---------------- Das Logfile ist die Hauptinformationsquelle zum Debuggen. Es zeichnet auf, was mit der Seite geschieht, während sie von Embperl bearbeitet wird. In Abhängigkeit von den Debugflags, logged Embperl folgende Dinge: Quellencode Umgebungsvariablen Formular daten Perlcode (Quelle + Ergebnis) Tabellenbearbeitung Eingabe-Tag-Bearbeitung HTTP headers Embperl Logdatei kann direkt im Browser angezeigt werden -------------------------------------------------------- Zur Fehlersuche kann Embperl veranlasst werden, an jedem Seitenanfang einen Link zur Logdatei anzuzeigen. Wenn man dem Link folgt, wird der Teil der Logdatei, welcher zu dem entsprechenden Request gehört angezeigt. Dabei werden unterschiedliche Einträge zur leichteren Orientierung verschiedenfarbig dargestellt. Embperl Fehlerseite enthält Links zum Logfile --------------------------------------------- Wenn die Links zur Logdatei freigeschaltet sind, werden auch in jeder Fehlerseite die Fehler direkt als Link dargestellt, die direkt auf die richtige Position im Logfile verweisen. So läßt sich einfach feststellen, was an dieser Stelle schief gelaufen ist. Datenbankzugriff ================ DBI --- Dies ist ein weiteres Beispiel für den Datenbankzugriff mittels DBI. Im Gegensatz zum vorhergehenden Beispiel arbeitet es aber mit expliziten Schleifen. [- # Mit der Datenbank verbinden $dbh = DBI->connect($DSN) ; # Vorbereiten des SQL Select $sth = $dbh -> prepare ("SELECT * from $table") ; # Abfrage ausführen $sth -> execute ; # Ermitteln der Feldnamen für die Überschrift in $head $head = $sth -> {NAME} ; -] [$ foreach $h @$head $] [$ endforeach $] [$ while $dat = $sth -> fetchrow_arrayref $] [$ foreach $v @$dat $] [$ endforeach $] [$ endwhile $]
[+ $h +]
[+ $v +]
DBIx::Recordset --------------- DBIx::Recordset ist ein Modul welches den Datenbankzugriff vereinfachen soll. Eine weiterführende Einführung zu DBIx::Recordset und Embperl findet sich in der iX 9/1999 unter http://www.heise.de/ix/artikel/1999/09/137/ . Datenbankabfrage Beispiel ------------------------- [-*set = DBIx::Recordset -> Search ({%fdat, ('!DataSource' => $DSN, '!Table' => $table, '$max' => 5,)}) ; -]
IDNAME
[+ $set[$row]{id} +] [+ $set[$row]{name} +]
[+ $set -> PrevNextForm ('Previous Records', 'Next Records', \%fdat) +] Search erzeugt ein Recordsetobjekt ---------------------------------- Search nimmt die Werte aus %fdat und benutzt diese um einen SQL WHERE Ausdruck zu erzeugen. Auf diese Weise hängt es davon ab, was an das Dokument für Daten gesandt werden, welche Anfrage ausgeführt wird. z.B. wenn man das Dokument mit http://host/mydoc.html?id=5 aufruft, werden alle Datensätze deren Feld id den Wert 5 enthält angezeigt. Die Daten können als Array oder mittels eines aktuellen Datensatzzeigers angesprochen werden -------------------------------------------------------------------------------------------- Das Ergebnis der Abfrage kann wie ein Array angesprochen werden (was nicht heißt, daß das ganze Array auch tatsächlich von der Datenbank angefordert wird). Alternativ können die Felder des aktuellen Record angesprochen werden. set[5]{id} Zugriff auf das Feld 'id' des sechsten gefundenen Datensatzes set{id} Zugriff auf das Feld 'id' des aktuellen Datensatzes Felder können mit ihren Namen angesprochen werden ------------------------------------------------- Während bei DBI Feldinhalte hauptsächlich über ihre Spaltennummern angesprochen werden, benutzt DBIx::Recordset Spaltennamen. Dies macht das Programm einfacher zu schreiben, leichter verständlich und unabhäniger von Veränderungen in der Datenbankstruktur. PrevNextForm erzeugt keinen/einen/zwei Schaltflächen je nachdem ob weitere Datensätze angezeigt werden müssen ------------------------------------------------------------------------------------------------------------- Die PrevNextButtons Funktion kann dazu benutzt werden um Schaltflächen zum Anzeigen der vorhergehenden bzw. folgenden Datensätze zu erzeugen. `PrevNextForm' generiert ein kleines Formular welches alle nötigen Daten als versteckte Felder enthält. Wie fürs Suchen, gibt es auch Funktionen für Insert/Update/Delete ----------------------------------------------------------------- Beispiel für Insert Wenn `%fdat' die Daten für einen neuen Datensatz enthält, fügt der folgende Code einen diesen der angegebenen Tabelle hinzu. [-*set = DBIx::Recordset -> Insert ({%fdat, ('!DataSource' => $DSN, '!Table' => $table)}) ; -] Datenbanktabellen können ebenso an einen Hash gebunden werden ------------------------------------------------------------- DBIx::Recordset kann ebenfalls eine Datenbanktabelle an einen Hash binden. Man muß lediglich den Primärschlüssel der Tabelle angeben und kann dann auf die Tabelle mittels eines Perl Hashs zugreifen. $set{5}{name} Zugriff auf Feld 'name' mit id=5 (id ist Primärschlüssel) Arbeiten mit mehreren Tabellen ------------------------------ DBIx::Recordset bietet zahlreiche Möglichkeiten um einfach mit mehreren Tabellen umgehen zu können. DBIx::Recordset versucht auf Grund der Namen innerhalb der Datenbank selbstständig Zusammenhänge zwischen Tabellen zu erkennen. Weitere Zusammenhänge können manuell angegeben werden. Mit diesen Informationen kann DBIx::Recordset automatisch Unterobjekte erzeugen, die die zum entsprechenden Datensatz zugehörigen Datensätze der verbundenen Tabelle enthalten. Ebenso ist es möglich das DBIx::Recordset einer Abfrage automatisch Felder hinzufügt, die den referenzierten Datensatz beschreiben. So ist es z.B. möglich, wenn in einer Tabelle die Kundennr enthalten ist, aus dem Kundenstammsatz automatisch den Namen des Kunden hinzuzufügen, ohne das diese jedesmal explizit angeben werden müßte. Sicherheit ========== Bei der Ausführung unter mod_perl, teilt sich jeglicher Perlcode einen Perlinterpreter. Das bedeutet, das jede Applikation auf alle Daten aller anderen Applikationen zugreifen kann. Embperl verwaltet einen separaten Namensraum für jedes Embperl Dokument, was ausreicht um versehentliches Überschreiben von Daten anderer Applikationen zu verhindern. Dieses Verfahren bietet jedoch keine wirkliche Sicherheit. Der Zugriff auf alle Daten ist möglich durch die explizite Angabe eines Package Namens. Safe namespaces --------------- Deshalb kann Embperl Safe.pm nutzen, um den Zugriff auf alle Namensräume außerhalb des eigentlichen Skripts zu unterbinden. Dadurch wird es z.B. möglich, Berechnungen innerhalb eines Perlmoduls durchzuführen und die Ergebnisse an ein Embperl Dokument zu übergeben. Wenn dieses in einem sicheren Namensraum läuft, kann es diese Ergebnisse darstellen, jedoch auf keine anderen Daten zugreifen. Dadurch wird es sicher, verschiedene Personen am Layout arbeiteten zu lassen. Operatoren Einschränkungen -------------------------- Safe.pm erlaubt es dem Administrator jeden Perl Opcode zu sperren. Dadurch wird es möglich zu kontrollieren, welche Perl Opcodes innerhalb der Seiten genutzt werden dürfen. Escaping/Unescaping =================== Quellendaten: Unescaping ------------------------ (sperren mit optRawInput) - konvertiert HTML escapes zu Zeichen (z.B. < zu <) - entfernt HTML tags aus dem Perlcode (z.B.
welches durch einen HTML Editor eingefügt wurde) Ausgabe: Escaping ----------------- (sperren mit escmode) - konvertiert Sonderzeichen nach HTML (z.B. < zu <)