This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: Text/Balanced, Next: Text/BasicTemplate, Prev: Text/Autoformat, Up: Module List Extract delimited text sequences from strings. ********************************************** NAME ==== Text::Balanced - Extract delimited text sequences from strings. SYNOPSIS ======== use Text::Balanced qw ( extract_delimited extract_bracketed extract_quotelike extract_codeblock extract_variable extract_tagged extract_multiple gen_delimited_pat gen_extract_tagged ); # Extract the initial substring of $text that is delimited by # two (unescaped) instances of the first character in $delim. ($extracted, $remainder) = extract_delimited($text,$delim); # Extract the initial substring of $text that is bracketed # with a delimiter(s) specified by $delim (where the string # in $delim contains one or more of '(){}[]<>'). ($extracted, $remainder) = extract_bracketed($text,$delim); # Extract the initial substring of $text that is bounded by # an HTML/XML tag. ($extracted, $remainder) = extract_tagged($text); # Extract the initial substring of $text that is bounded by # a C...C pair. Don't allow nested C tags ($extracted, $remainder) = extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]}); # Extract the initial substring of $text that represents a # Perl "quote or quote-like operation" ($extracted, $remainder) = extract_quotelike($text); # Extract the initial substring of $text that represents a block # of Perl code, bracketed by any of character(s) specified by $delim # (where the string $delim contains one or more of '(){}[]<>'). ($extracted, $remainder) = extract_codeblock($text,$delim); # Extract the initial substrings of $text that would be extracted by # one or more sequential applications of the specified functions # or regular expressions @extracted = extract_multiple($text, [ \&extract_bracketed, \&extract_quotelike, \&some_other_extractor_sub, qr/[xyz]*/, 'literal', ]); # Create a string representing an optimized pattern (a la Friedl) # that matches a substring delimited by any of the specified characters # (in this case: any type of quote or a slash) $patstring = gen_delimited_pat(q{'"`/}); # Generate a reference to an anonymous sub that is just like extract_tagged # but pre-compiled and optimized for a specific pair of tags, and consequently # much faster (i.e. 3 times faster). It uses qr// for better performance on # repeated calls, so it only works under Perl 5.005 or later. $extract_head = gen_extract_tagged('',''); ($extracted, $remainder) = $extract_head->($text); DESCRIPTION =========== The various `extract_...' subroutines may be used to extract a delimited string (possibly after skipping a specified prefix string). The search for the string always begins at the current pos location of the string's variable (or at index zero, if no pos position is defined). General behaviour in list contexts ---------------------------------- In a list context, all the subroutines return a list, the first three elements of which are always: [0] The extracted string, including the specified delimiters. If the extraction fails an empty string is returned. [1] The remainder of the input string (i.e. the characters after the extracted string). On failure, the entire string is returned. [2] The skipped prefix (i.e. the characters before the extracted string). On failure, the empty string is returned. Note that in a list context, the contents of the original input text (the first argument) are not modified in any way. However, if the input text was passed in a variable, that variable's pos value is updated to point at the first character after the extracted text. That means that in a list context the various subroutines can be used much like regular expressions. For example: while ( $next = (extract_quotelike($text))[0] ) { # process next quote-like (in $next) } General behaviour in scalar and void contexts --------------------------------------------- In a scalar context, the extracted string is returned, having first been removed from the input text. Thus, the following code also processes each quote-like operation, but actually removes them from $text: while ( $next = extract_quotelike($text) ) { # process next quote-like (in $next) } Note that if the input text is a read-only string (i.e. a literal), no attempt is made to remove the extracted text. In a void context the behaviour of the extraction subroutines is exactly the same as in a scalar context, except (of course) that the extracted substring is not returned. A note about prefixes --------------------- Prefix patterns are matched without any trailing modifiers (`/gimsox' etc.) This can bite you if you're expecting a prefix specification like '.*?(?=

)' to skip everything up to the first

tag. Such a prefix pattern will only succeed if the

tag is on the current line, since . normally doesn't match newlines. To overcome this limitation, you need to turn on /s matching within the prefix pattern, using the `(?s)' directive: '(?s).*?(?=

)' `extract_delimited' ------------------- The `extract_delimited' function formalizes the common idiom of extracting a single-character-delimited substring from the start of a string. For example, to extract a single-quote delimited string, the following code is typically used: ($remainder = $text) =~ s/\A('(\\.|[^'])*')//s; $extracted = $1; but with `extract_delimited' it can be simplified to: ($extracted,$remainder) = extract_delimited($text, "'"); `extract_delimited' takes up to four scalars (the input text, the delimiters, a prefix pattern to be skipped, and any escape characters) and extracts the initial substring of the text that is appropriately delimited. If the delimiter string has multiple characters, the first one encountered in the text is taken to delimit the substring. The third argument specifies a prefix pattern that is to be skipped (but must be present!) before the substring is extracted. The final argument specifies the escape character to be used for each delimiter. All arguments are optional. If the escape characters are not specified, every delimiter is escaped with a backslash (\). If the prefix is not specified, the pattern `'\s*'' - optional whitespace - is used. If the delimiter set is also not specified, the set `/["'`]/' is used. If the text to be processed is not specified either, $_ is used. In list context, `extract_delimited' returns a array of three elements, the extracted substring (*including the surrounding delimiters*), the remainder of the text, and the skipped prefix (if any). If a suitable delimited substring is not found, the first element of the array is the empty string, the second is the complete original text, and the prefix returned in the third element is an empty string. In a scalar context, just the extracted substring is returned. In a void context, the extracted substring (and any prefix) are simply removed from the beginning of the first argument. Examples: # Remove a single-quoted substring from the very beginning of $text: $substring = extract_delimited($text, "'", ''); # Remove a single-quoted Pascalish substring (i.e. one in which # doubling the quote character escapes it) from the very # beginning of $text: $substring = extract_delimited($text, "'", '', "'"); # Extract a single- or double- quoted substring from the # beginning of $text, optionally after some whitespace # (note the list context to protect $text from modification): ($substring) = extract_delimited $text, q{"'}; # Delete the substring delimited by the first '/' in $text: $text = join '', (extract_delimited($text,'/','[^/]*')[2,1]; Note that this last example is not the same as deleting the first quote-like pattern. For instance, if $text contained the string: "if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }" then after the deletion it would contain: "if ('.$UNIXCMD/s) { $cmd = $1; }" not: "if ('./cmd' =~ ms) { $cmd = $1; }" See `"extract_quotelike"' in this node for a (partial) solution to this problem. `extract_bracketed' ------------------- Like `"extract_delimited"', the `extract_bracketed' function takes up to three optional scalar arguments: a string to extract from, a delimiter specifier, and a prefix pattern. As before, a missing prefix defaults to optional whitespace and a missing text defaults to $_. However, a missing delimiter specifier defaults to `'{}()[]<>'' (see below). `extract_bracketed' extracts a balanced-bracket-delimited substring (using any one (or more) of the user-specified delimiter brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it will also respect quoted unbalanced brackets (see below). A "delimiter bracket" is a bracket in list of delimiters passed as `extract_bracketed''s second argument. Delimiter brackets are specified by giving either the left or right (or both!) versions of the required bracket(s). Note that the order in which two or more delimiter brackets are specified is not significant. A "balanced-bracket-delimited substring" is a substring bounded by matched brackets, such that any other (left or right) delimiter bracket *within* the substring is also matched by an opposite (right or left) delimiter bracket *at the same level of nesting*. Any type of bracket not in the delimiter list is treated as an ordinary character. In other words, each type of bracket specified as a delimiter must be balanced and correctly nested within the substring, and any other kind of ("non-delimiter") bracket in the substring is ignored. For example, given the string: $text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }"; then a call to `extract_bracketed' in a list context: @result = extract_bracketed( $text, '{}' ); would return: ( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" ) since both sets of `'{..}'' brackets are properly nested and evenly balanced. (In a scalar context just the first element of the array would be returned. In a void context, $text would be replaced by an empty string.) Likewise the call in: @result = extract_bracketed( $text, '{[' ); would return the same result, since all sets of both types of specified delimiter brackets are correctly nested and balanced. However, the call in: @result = extract_bracketed( $text, '{([<' ); would fail, returning: ( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }" ); because the embedded pairs of `'(..)''s and `'[..]''s are "cross-nested" and the embedded `'>'' is unbalanced. (In a scalar context, this call would return an empty string. In a void context, $text would be unchanged.) Note that the embedded single-quotes in the string don't help in this case, since they have not been specified as acceptable delimiters and are therefore treated as non-delimiter characters (and ignored). However, if a particular species of quote character is included in the delimiter specification, then that type of quote will be correctly handled. for example, if $text is: $text = 'link'; then @result = extract_bracketed( $text, '<">' ); returns: ( '', 'link', "" ) as expected. Without the specification of `"' as an embedded quoter: @result = extract_bracketed( $text, '<>' ); the result would be: ( 'link', "" ) In addition to the quote delimiters `'', `"', and ``', full Perl quote-like quoting (i.e. q{string}, qq{string}, etc) can be specified by including the letter 'q' as a delimiter. Hence: @result = extract_bracketed( $text, '' ); would correctly match something like this: $text = ''; See also: `"extract_quotelike"' and `"extract_codeblock"'. `extract_tagged' ---------------- `extract_tagged' extracts and segments text between (balanced) specified tags. The subroutine takes up to five optional arguments: 1. A string to be processed ($_ if the string is omitted or undef) 2. A string specifying a pattern to be matched as the opening tag. If the pattern string is omitted (or undef) then a pattern that matches any standard HTML/XML tag is used. 3. A string specifying a pattern to be matched at the closing tag. If the pattern string is omitted (or undef) then the closing tag is constructed by inserting a / after any leading bracket characters in the actual opening tag that was matched (not the pattern that matched the tag). For example, if the opening tag pattern is specified as `'{{\w+}}'' and actually matched the opening tag `"{{DATA}}"', then the constructed closing tag would be `"{{/DATA}}"'. 4. A string specifying a pattern to be matched as a prefix (which is to be skipped). If omitted, optional whitespace is skipped. 5. A hash reference containing various parsing options (see below) The various options that can be specified are: `reject => $listref' The list reference contains one or more strings specifying patterns that must not appear within the tagged text. For example, to extract an HTML link (which should not contain nested links) use: extract_tagged($text, '', '', undef, {reject => ['']} ); `ignore => $listref' The list reference contains one or more strings specifying patterns that are not be be treated as nested tags within the tagged text (even if they would match the start tag pattern). For example, to extract an arbitrary XML tag, but ignore "empty" elements: extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} ); (also see `"gen_delimited_pat"' in this node below). `fail => $str' The fail option indicates the action to be taken if a matching end tag is not encountered (i.e. before the end of the string or some `reject' pattern matches). By default, a failure to match a closing tag causes `extract_tagged' to immediately fail. However, if the string value associated with is "MAX", then `extract_tagged' returns the complete text up to the point of failure. If the string is "PARA", `extract_tagged' returns only the first paragraph after the tag (up to the first line that is either empty or contains only whitespace characters). If the string is "", the the default behaviour (i.e. failure) is reinstated. For example, suppose the start tag "/para" introduces a paragraph, which then continues until the next "/endpara" tag or until another "/para" tag is encountered: $text = "/para line 1\n\nline 3\n/para line 4"; extract_tagged($text, '/para', '/endpara', undef, {reject => '/para', fail => MAX ); # EXTRACTED: "/para line 1\n\nline 3\n" Suppose instead, that if no matching "/endpara" tag is found, the "/para" tag refers only to the immediately following paragraph: $text = "/para line 1\n\nline 3\n/para line 4"; extract_tagged($text, '/para', '/endpara', undef, {reject => '/para', fail => MAX ); # EXTRACTED: "/para line 1\n" Note that the specified fail behaviour applies to nested tags as well. On success in a list context, an array of 6 elements is returned. The elements are: [0] the extracted tagged substring (including the outermost tags), [1] the remainder of the input text, [2] the prefix substring (if any), [3] the opening tag [4] the text between the opening and closing tags [5] the closing tag (or "" if no closing tag was found) On failure, all of these values (except the remaining text) are undef. In a scalar context, `extract_tagged' returns just the complete substring that matched a tagged text (including the start and end tags). undef is returned on failure. In addition, the original input text has the returned substring (and any prefix) removed from it. In a void context, the input text just has the matched substring (and any specified prefix) removed. `gen_extract_tagged' -------------------- (Note: This subroutine is only available under Perl5.005) `gen_extract_tagged' generates a new anonymous subroutine which extracts text between (balanced) specified tags. In other words, it generates a function identical in function to `extract_tagged'. The difference between `extract_tagged' and the anonymous subroutines generated by `gen_extract_tagged', is that those generated subroutines: * do not have to reparse tag specification or parsing options every time they are called (whereas `extract_tagged' has to effectively rebuild its tag parser on every call); * make use of the new qr// construct to pre-compile the regexes they use (whereas `extract_tagged' uses standard string variable interpolation to create tag-matching patterns). The subroutine takes up to four optional arguments (the same set as `extract_tagged' except for the string to be processed). It returns a reference to a subroutine which in turn takes a single argument (the text to be extracted from). In other words, the implementation of `extract_tagged' is exactly equivalent to: sub extract_tagged { my $text = shift; $extractor = gen_extract_tagged(@_); return $extractor->($text); } (although `extract_tagged' is not currently implemented that way, in order to preserve pre-5.005 compatibility). Using `gen_extract_tagged' to create extraction functions for specific tags is a good idea if those functions are going to be called more than once, since their performance is typically twice as good as the more general-purpose `extract_tagged'. `extract_quotelike' ------------------- `extract_quotelike' attempts to recognize, extract, and segment any one of the various Perl quotes and quotelike operators (see `perlop(3)' in this node) Nested backslashed delimiters, embedded balanced bracket delimiters (for the quotelike operators), and trailing modifiers are all caught. For example, in: extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #' extract_quotelike ' "You said, \"Use sed\"." ' extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; ' extract_quotelike ' tr/\\\/\\\\/\\\//ds; ' the full Perl quotelike operations are all extracted correctly. Note too that, when using the /x modifier on a regex, any comment containing the current pattern delimiter will cause the regex to be immediately terminated. In other words: 'm / (?i) # CASE INSENSITIVE [a-z_] # LEADING ALPHABETIC/UNDERSCORE [a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS /x' will be extracted as if it were: 'm / (?i) # CASE INSENSITIVE [a-z_] # LEADING ALPHABETIC/' This behaviour is identical to that of the actual compiler. `extract_quotelike' takes two arguments: the text to be processed and a prefix to be matched at the very beginning of the text. If no prefix is specified, optional whitespace is the default. If no text is given, $_ is used. In a list context, an array of 11 elements is returned. The elements are: [0] the extracted quotelike substring (including trailing modifiers), [1] the remainder of the input text, [2] the prefix substring (if any), [3] the name of the quotelike operator (if any), [4] the left delimiter of the first block of the operation, [5] the text of the first block of the operation (that is, the contents of a quote, the regex of a match or substitution or the target list of a translation), [6] the right delimiter of the first block of the operation, [7] the left delimiter of the second block of the operation (that is, if it is a s, tr, or y), [8] the text of the second block of the operation (that is, the replacement of a substitution or the translation list of a translation), [9] the right delimiter of the second block of the operation (if any), [10] the trailing modifiers on the operation (if any). For each of the fields marked "(if any)" the default value on success is an empty string. On failure, all of these values (except the remaining text) are undef. In a scalar context, `extract_quotelike' returns just the complete substring that matched a quotelike operation (or undef on failure). In a scalar or void context, the input text has the same substring (and any specified prefix) removed. Examples: # Remove the first quotelike literal that appears in text $quotelike = extract_quotelike($text,'.*?'); # Replace one or more leading whitespace-separated quotelike # literals in $_ with "" do { $_ = join '', (extract_quotelike)[2,1] } until $@; # Isolate the search pattern in a quotelike operation from $text ($op,$pat) = (extract_quotelike $text)[3,5]; if ($op =~ /[ms]/) { print "search pattern: $pat\n"; } else { print "$op is not a pattern matching operation\n"; } `extract_quotelike' and "here documents" ---------------------------------------- `extract_quotelike' can successfully extract "here documents" from an input string, but with an important caveat in list contexts. Unlike other types of quote-like literals, a here document is rarely a contiguous substring. For example, a typical piece of code using here document might look like this: <<'EOMSG' || die; This is the message. EOMSG exit; Given this as an input string in a scalar context, `extract_quotelike' would correctly return the string "<<'EOMSG'\nThis is the message.\nEOMSG", leaving the string " || die;\nexit;" in the original variable. In other words, the two separate pieces of the here document are successfully extracted and concatenated. In a list context, `extract_quotelike' would return the list [0] "<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted here document, including fore and aft delimiters), [1] " || die;\nexit;" (i.e. the remainder of the input text, concatenated), [2] "" (i.e. the prefix substring - trivial in this case), [3] "<<" (i.e. the "name" of the quotelike operator) [4] "'EOMSG'" (i.e. the left delimiter of the here document, including any quotes), [5] "This is the message.\n" (i.e. the text of the here document), [6] "EOMSG" (i.e. the right delimiter of the here document), [7..10] "" (a here document has no second left delimiter, second text, second right delimiter, or trailing modifiers). However, the matching position of the input variable would be set to "exit;" (i.e. after the closing delimiter of the here document), which would cause the earlier " || die;\nexit;" to be skipped in any sequence of code fragment extractions. To avoid this problem, when it encounters a here document whilst extracting from a modifiable string, `extract_quotelike' silently rearranges the string to an equivalent piece of Perl: <<'EOMSG' This is the message. EOMSG || die; exit; in which the here document *is* contiguous. It still leaves the matching position after the here document, but now the rest of the line on which the here document starts is not skipped. To prevent from mucking about with the input in this way (this is the only case where a list-context `extract_quotelike' does so), you can pass the input variable as an interpolated literal: $quotelike = extract_quotelike("$var"); `extract_codeblock' ------------------- `extract_codeblock' attempts to recognize and extract a balanced bracket delimited substring that may contain unbalanced brackets inside Perl quotes or quotelike operations. That is, `extract_codeblock' is like a combination of `"extract_bracketed"' and `"extract_quotelike"'. `extract_codeblock' takes the same initial three parameters as `extract_bracketed': a text to process, a set of delimiter brackets to look for, and a prefix to match first. It also takes an optional fourth parameter, which allows the outermost delimiter brackets to be specified separately (see below). Omitting the first argument (input text) means process $_ instead. Omitting the second argument (delimiter brackets) indicates that only `'{'' is to be used. Omitting the third argument (prefix argument) implies optional whitespace at the start. Omitting the fourth argument (outermost delimiter brackets) indicates that the value of the second argument is to be used for the outermost delimiters. Once the prefix an dthe outermost opening delimiter bracket have been recognized, code blocks are extracted by stepping through the input text and trying the following alternatives in sequence: 1. Try and match a closing delimiter bracket. If the bracket was the same species as the last opening bracket, return the substring to that point. If the bracket was mismatched, return an error. 2. Try to match a quote or quotelike operator. If found, call `extract_quotelike' to eat it. If `extract_quotelike' fails, return the error it returned. Otherwise go back to step 1. 3. Try to match an opening delimiter bracket. If found, call `extract_codeblock' recursively to eat the embedded block. If the recursive call fails, return an error. Otherwise, go back to step 1. 4. Unconditionally match a bareword or any other single character, and then go back to step 1. Examples: # Find a while loop in the text if ($text =~ s/.*?while\s*\{/{/) { $loop = "while " . extract_codeblock($text); } # Remove the first round-bracketed list (which may include # round- or curly-bracketed code blocks or quotelike operators) extract_codeblock $text, "(){}", '[^(]*'; The ability to specify a different outermost delimiter bracket is useful in some circumstances. For example, in the Parse::RecDescent module, parser actions which are to be performed only on a successful parse are specified using a `' directive. For example: sentence: subject verb object Parse::RecDescent uses `extract_codeblock($text, '{}<>')' to extract the code within the `' directive, but there's a problem. A deferred action like this: 10) {$count--}} > will be incorrectly parsed as: because the "less than" operator is interpreted as a closing delimiter. But, by extracting the directive using `extract_codeblock($text, '{}', undef, '<>')' the '>' character is only treated as a delimited at the outermost level of the code block, so the directive is parsed correctly. `extract_multiple' ------------------ The `extract_multiple' subroutine takes a string to be processed and a list of extractors (subroutines or regular expressions) to apply to that string. In an array context `extract_multiple' returns an array of substrings of the original string, as extracted by the specified extractors. In a scalar context, `extract_multiple' returns the first substring successfully extracted from the original string. In both scalar and void contexts the original string has the first successfully extracted substring removed from it. In all contexts `extract_multiple' starts at the current pos of the string, and sets that pos appropriately after it matches. Hence, the aim of of a call to `extract_multiple' in a list context is to split the processed string into as many non-overlapping fields as possible, by repeatedly applying each of the specified extractors to the remainder of the string. Thus `extract_multiple' is a generalized form of Perl's split subroutine. The subroutine takes up to four optional arguments: 1. A string to be processed ($_ if the string is omitted or undef) 2. A reference to a list of subroutine references and/or qr// objects and/or literal strings and/or hash references, specifying the extractors to be used to split the string. If this argument is omitted (or undef) the list: [ sub { extract_variable($_[0], '') }, sub { extract_quotelike($_[0],'') }, sub { extract_codeblock($_[0],'{}','') }, ] is used. 3. An number specifying the maximum number of fields to return. If this argument is omitted (or undef), split continues as long as possible. If the third argument is N, then extraction continues until N fields have been successfully extracted, or until the string has been completely processed. Note that in scalar and void contexts the value of this argument is automatically reset to 1 (under -w, a warning is issued if the argument has to be reset). 4. A value indicating whether unmatched substrings (see below) within the text should be skipped or returned as fields. If the value is true, such substrings are skipped. Otherwise, they are returned. The extraction process works by applying each extractor in sequence to the text string. If the extractor is a subroutine it is called in a list context and is expected to return a list of a single element, namely the extracted text. Note that the value returned by an extractor subroutine need not bear any relationship to the corresponding substring of the original text (see examples below). If the extractor is a precompiled regular expression or a string, it is matched against the text in a scalar context with a leading '\G' and the gc modifiers enabled. The extracted value is either $1 if that variable is defined after the match, or else the complete match (i.e. $&). If the extractor is a hash reference, it must contain exactly one element. The value of that element is one of the above extractor types (subroutine reference, regular expression, or string). The key of that element is the name of a class into which the successful return value of the extractor will be blessed. If an extractor returns a defined value, that value is immediately treated as the next extracted field and pushed onto the list of fields. If the extractor was specified in a hash reference, the field is also blessed into the appropriate class, If the extractor fails to match (in the case of a regex extractor), or returns an empty list or an undefined value (in the case of a subroutine extractor), it is assumed to have failed to extract. If none of the extractor subroutines succeeds, then one character is extracted from the start of the text and the extraction subroutines reapplied. Characters which are thus removed are accumulated and eventually become the next field (unless the fourth argument is true, in which case they are disgarded). For example, the following extracts substrings that are valid Perl variables: @fields = extract_multiple($text, [ sub { extract_variable($_[0]) } ], undef, 1); This example separates a text into fields which are quote delimited, curly bracketed, and anything else. The delimited and bracketed parts are also blessed to identify them (the "anything else" is unblessed): @fields = extract_multiple($text, [ { Delim => sub { extract_delimited($_[0],q{'"}) } }, { Brack => sub { extract_bracketed($_[0],'{}') } }, ]); This call extracts the next single substring that is a valid Perl quotelike operator (and removes it from $text): $quotelike = extract_multiple($text, [ sub { extract_quotelike($_[0]) }, ], undef, 1); Finally, here is yet another way to do comma-separated value parsing: @fields = extract_multiple($csv_text, [ sub { extract_delimited($_[0],q{'"}) }, qr/([^,]+)(.*)/, ], undef,1); The list in the second argument means: *"Try and extract a ' or " delimited string, otherwise extract anything up to a comma..."*. The undef third argument means: *"...as many times as possible..."*, and the true value in the fourth argument means *"...discarding anything else that appears (i.e. the commas)"*. If you wanted the commas preserved as separate fields (i.e. like split does if your split pattern has capturing parentheses), you would just make the last parameter undefined (or remove it). `gen_delimited_pat' ------------------- The `gen_delimited_pat' subroutine takes a single (string) argument and builds a Friedl-style optimized regex that matches a string delimited by any one of the characters in the single argument. For example: gen_delimited_pat(q{'"}) returns the regex: (?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\') Note that the specified delimiters are automatically quotemeta'd. A typical use of `gen_delimited_pat' would be to build special purpose tags for `extract_tagged'. For example, to properly ignore "empty" XML elements (which might contain quoted strings): my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>'; extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} ); `gen_delimited_pat' may also be called with an optional second argument, which specifies the "escape" character(s) to be used for each delimiter. For example to match a Pascal-style string (where ' is the delimiter and " is a literal ' within the string): gen_delimited_pat(q{'},q{'}); Different escape characters can be specified for different delimiters. For example, to specify that '/' is the escape for single quotes and '%' is the escape for double quotes: gen_delimited_pat(q{'"},q{/%}); If more delimiters than escape chars are specified, the last escape char is used for the remaining delimiters. If no escape char is specified for a given specified delimiter, '\' is used. Note that `gen_delimited_pat' was previously called `delimited_pat'. That name may still be used, but is now deprecated. DIAGNOSTICS =========== In a list context, all the functions return `(undef,$original_text)' on failure. In a scalar context, failure is indicated by returning undef (in this case the input text is not modified in any way). In addition, on failure in any context, the `$@' variable is set. Accessing `$@->{error}' returns one of the error diagnostics listed below. Accessing `$@->{pos}' returns the offset into the original string at which the error was detected (although not necessarily where it occurred!) Printing `$@' directly produces the error message, with the offset appended. On success, the `$@' variable is guaranteed to be undef. The available diagnostics are: `Did not find a suitable bracket: "%s"' The delimiter provided to `extract_bracketed' was not one of `'()[]<>{}''. `Did not find prefix: /%s/' A non-optional prefix was specified but wasn't found at the start of the text. `Did not find opening bracket after prefix: "%s"' `extract_bracketed' or `extract_codeblock' was expecting a particular kind of bracket at the start of the text, and didn't find it. `No quotelike operator found after prefix: "%s"' `extract_quotelike' didn't find one of the quotelike operators q, qq, `qw', `qx', s, tr or y at the start of the substring it was extracting. `Unmatched closing bracket: "%c"' `extract_bracketed', `extract_quotelike' or `extract_codeblock' encountered a closing bracket where none was expected. `Unmatched opening bracket(s): "%s"' `extract_bracketed', `extract_quotelike' or `extract_codeblock' ran out of characters in the text before closing one or more levels of nested brackets. `Unmatched embedded quote (%s)' `extract_bracketed' attempted to match an embedded quoted substring, but failed to find a closing quote to match it. `Did not find closing delimiter to match '%s'' `extract_quotelike' was unable to find a closing delimiter to match the one that opened the quote-like operation. `Mismatched closing bracket: expected "%c" but found "%s"' `extract_bracketed', `extract_quotelike' or `extract_codeblock' found a valid bracket delimiter, but it was the wrong species. This usually indicates a nesting error, but may indicate incorrect quoting or escaping. `No block delimiter found after quotelike "%s"' `extract_quotelike' or `extract_codeblock' found one of the quotelike operators q, qq, `qw', `qx', s, tr or y without a suitable block after it. `Did not find leading dereferencer' `extract_variable' was expecting one of '$', '@', or '%' at the start of a variable, but didn't find any of them. `Bad identifier after dereferencer' `extract_variable' found a '$', '@', or '%' indicating a variable, but that character was not followed by a legal Perl identifier. `Did not find expected opening bracket at %s' `extract_codeblock' failed to find any of the outermost opening brackets that were specified. `Improperly nested codeblock at %s' A nested code block was found that started with a delimiter that was specified as being only to be used as an outermost bracket. `Missing second block for quotelike "%s"' `extract_codeblock' or `extract_quotelike' found one of the quotelike operators s, tr or y followed by only one block. `No match found for opening bracket' `extract_codeblock' failed to find a closing bracket to match the outermost opening bracket. `Did not find opening tag: /%s/' `extract_tagged' did not find a suitable opening tag (after any specified prefix was removed). `Unable to construct closing tag to match: /%s/' `extract_tagged' matched the specified opening tag and tried to modify the matched text to produce a matching closing tag (because none was specified). It failed to generate the closing tag, almost certainly because the opening tag did not start with a bracket of some kind. `Found invalid nested tag: %s' `extract_tagged' found a nested tag that appeared in the "reject" list (and the failure mode was not "MAX" or "PARA"). `Found unbalanced nested tag: %s' `extract_tagged' found a nested opening tag that was not matched by a corresponding nested closing tag (and the failure mode was not "MAX" or "PARA"). `Did not find closing tag' `extract_tagged' reached the end of the text without finding a closing tag to match the original opening tag (and the failure mode was not "MAX" or "PARA"). AUTHOR ====== Damian Conway (damian@conway.org) BUGS AND IRRITATIONS ==================== There are undoubtedly serious bugs lurking somewhere in this code, if only because parts of it give the impression of understanding a great deal more about Perl than they really do. Bug reports and other feedback are most welcome. COPYRIGHT ========= Copyright (c) 1997-2000, Damian Conway. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)  File: pm.info, Node: Text/BasicTemplate, Next: Text/Bastardize, Prev: Text/Balanced, Up: Module List Simple lexical text/html/etc template parser ******************************************** NAME ==== Text::BasicTemplate -- Simple lexical text/html/etc template parser SYNOPSIS ======== use Text::BasicTemplate; $bt = Text::BasicTemplate->new; my %dict = ( name => 'John', location => sub { hostname() }, condiments => [ 'Salt', 'Pepper', 'Catsup' ], sideeffects => { 'Salt' => 'causes high blood pressure', 'Pepper' => 'causes mariachi music', 'Catsup' => 'brings on warner bros. cartoons' }, new => int rand 2 ); $tmpl = "Hello, %name%; your mail is in %$MAIL%. Welcome to %location%!"; print $bt->parse(\$tmpl,\%dict); $tmpl = "%if new%First time, %name%?%fi%". " Care for some %condiments%? ". " They are bad for you. %sideeffects%." $bt->{hash_specifier}->{condiments} = ' '; print $bt->parse(\$tmpl,\%dict); DESCRIPTION =========== *Text::BasicTemplate* is a relatively straightforward template parsing module. Its overall function is to permit the separation of format-dependent output from code. This module provides standard key/value substitutions, lexical evaluation/parsing, customizable formatting of perl datatypes, and assorted utility functions. Templates may be structured by the use of arbitrarily nestable if-conditions (including elsif and else), and by the use of subroutine substitutions to provide list parsing. In general, the syntax for conditionals is that of perl itself. Text::BasicTemplate attempts to be as fast and as secure as possible. It may be safely used upon tainted templates and with tainted substitutions without fear of execution of any malicious code. GETTING STARTED =============== If you have previously used Text::BasicTemplate v0.x, it is important to read the COMPATIBILITY section - many things have changed, and compatibility is not guaranteed to be preserved in future versions. In general, start with the SYNTAX section, and be sure to at least skim the new() section (for configuration settings) and parse() section (for an explanation of the dictionary). SYNTAX ====== One of the difficulties in employing a new template parser is picking up the apropriate syntax. Text::BasicTemplate does not spare you that, but it does adhere fairly closely to the syntax of perl itself with respect to operators, conditional operations, template subroutine calls, etc. Anything to which Text::BasicTemplate should pay attention in a template is enclosed in percentage signs (%) - any such segments will be interpreted as identifiers, operations, conditionals, or apropriate combinations thereof. The simplest of these are variable substitutions; if parse() was passed a dictionary containing the pair (foo => "bar"), any instances of %foo% in the template will be evaluated as "bar." Other variable substitutions are available for lists and hashes, passed by reference in the parse() dictionary, as in (bar => \@r, snaf => \%h). In such a case %bar% will be evaluated to the contents of @r, and %snaf% to the contents of %h. Both will be formatted according to the configured delimiters (see LIST/HASH FORMATTING). Subroutine references may also be included in the dictionary; in their simple form, given ( subref => \&myfunction ), %subref% in the template will be evaluated to whatever is returned from &myfunction(). For more detail and features in subroutine handling, see *SUBROUTINE SUBTITUTIONS*. In v0.9.7, BasicTemplate introduced simple conditional evaluation, providing one-level equality/inequality comparisons. In 2.0, after a total rewrite, the conditional evaluation was replaced with a lexically parsed scoping evaluation, providing arbitrarily deep nesting, most major unary and binary perl comparison operators, arbitrary combination of operations, nonconditional evaluation, etc. For the full explanation, read on: SCOPING ------- Scoped evaluation is available to arbitrary depths, following the usual if/elsif/else pattern. if conditions are terminated by a *fi*. By example: # single if %if % %fi% # if-else %if % %else% %fi% # if-elsif %if % %elsif % %fi% # if-else-elsif %if % %elsif % %else% %fi% A block above is some amount of further template contents, including none (%if %%fi% is perfectly valid, albeit not generally useful). A block may contain further conditions. Dictionary variables used in a conditional will only be evaluated if they come into scope - for example, an elsif will not be evaluated unless its preceeding if or elsif evaluted false - the principal consequence of this is that subroutines referenced in a conditional will be called only if they come into scope per the above. IDENTIFIERS ----------- Numeric literals may be given without alteration, e.g. %123%. String literals should be given in double quotes, e.g. %"hello"%, or in single quotes, e.g. %'goodbye'%. Either sort may contain quotes of the other sort. Scalar, list and hash variables should be given by name, e.g. %foo%. %% gives a literal % sign and is considered normal text. Environment variables may be used as %$PATH%. Subroutine references should generally be referenced as %&foo%, or %&foo(arg1,arg2,...)% as apropriate. %foo% may be used for subroutines that return a scalar and will not require further parsing of their output - see SUBROUTINE SUBSTITUTIONS. EVALUATION ---------- Statements, conditional or otherwise, may be used outside of if/else contexts, and will have the results of the evaluation inserted at the point in which they occurred in the template. If used in an if/else statement, they will be evaluated, but the apropriate block will be output instead (pretty much the usual, IOW). *There is no operator precedence or conditional short-circuiting.* %1 || 2% will evaluate both 1 and 2 (and return 2). Evaluation order is not guaranteed. For all matters requiring precedence, parentheses should be employed (e.g. %1 && (0 || 3)%). Most of the perl unary and binary operators are supported; the trinary conditional is not. Operators presently provided are as follows: *eq ne lt le gt ge* - identical to their perl equivalents. Return 1 or false. *=~ !~* - also equivalent to the perl versions, but must be enabled by setting *enable_pattern_operator* true (see new()), as a malformed pattern may kill the script - so do not use them if you think you might be evaluating untrusted untrusted templates. The form for these is =~ pattern, not =~ /pattern/. *== != < <= > >= <=>* - perl equivalent *&& and || or* - the two ands and the two ors are considered equivalent, as there is no operator precedence in BasicTemplate. && and and return the value of the last operand. *. x* - perl equivalent; operand for x must be numeric. *+ - * / *** - perl equivalent, divide-by-zero will be checked. *div mod* - equivalent to int(x/y) and x % y respectively. *^ & | << >>* - perl equivalent *! defined* - perl equivalent. Examples: %foo + bar% - evaluates to result of foo+bar, where foo and bar are variables given in the dictionary. %if foo && (bar || snaf)% %fi% - evaluates foo, bar and snaf, outputs the block if the foo and one or more of bar and snaf were true. %"your name: " . &yourname% - outputs the string "your name: ", followed by whatever was returned by the subroutine referenced by the dictionary entry for yourname. %if $MAIL =~ Maildir% Bernstein would be proud. %else% Eric Allman wants you for a sunbeam. %fi% - evaluates according to whether the environment variable $MAIL contains the pattern 'Maildir.' Note that blocks inside conditional statements begin immediately following the closing %, so in the above examples, the newline and spaces would be considered part of the block and output if the condition evaluated true. This is acceptable for most whitespace-independent usages, but you should not include whitespace in a conditional block if you do not want it in the output. LIST/HASH FORMATTING -------------------- List references will be parsed and delimited according to $obj->{list_delimiter}->{listname} if supplied, and $obj->{list_delimiter}->{__default} if not (the latter is set with the default_list_delimiter argument to new()). The default is ", ". Hash references will be delimited using $obj->{hash_delimiter}->{hashname} between pairs, and $obj->{hash_specifier}->{hashname} between key and value. As above, __default will be used if a delimiter has not been specified for the specific variable. The defaults are ", " and "=" respectively. Example: $bt = Text::BasicTemplate->new(default_list_delimiter => ' and'); $ss = "path: %path%" . "\n" . "env: %env%"; $bt->{hash_specifier}->{env} = " is "; $bt->{hash_delimiter}->{env} = ", "; print $bt->parse(\$ss, { path => [ split(/:/,$ENV{PATH}) ], env => \%ENV }); Output from the above would be of the form: /bin and /usr/bin and /usr/local/bin SHELL is bash, VISUAL is emacs, RSYNC_RSH is ssh SUBROUTINE SUBSTITUTIONS ------------------------ Subroutine references are something of a special-case in Text::BasicTemplate. In a simple form, they can be used thusly: sub heart_of_oak { return "me lads, 'tis to glory we steer"; } $bt = Text::BasicTemplate->new(); $ss = "come cheer up %&rest_of_verse%"; %ov = ( rest_of_verse => \&heart_of_oak ); print $bt->parse(\$ss,\%ov); This would output "come cheer up me lads, 'tis to glory we steer," by calling &heart_of_oak() and inserting its return value into the template. You can pass literals and variables defined in the template to a subroutine, as follows: sub heart_of_oak { my @lines = ( "come cheer up me lads", "'tis to glory we steer", "to find something new in this wonderful year" ); my $which = shift; my $loud = shift || 0; return $loud ? uc $lines[$which] : $lines[$which]; } $bt = Text::BasicTemplate->new(); $ss = "song: %&song(1,$loud)%, %&song(2,$loud)%, %&song(3,$loud)%"; print $bt->parse(\$ss, { song => \&heart_of_oak, loud => 1 }); This would produce the lines of the song, separated by ", "; as written above (with loud == 1 in the dictionary), it will be shouted (inserted in capitals, as per the call to uc()) - in the template, the use of $variable in a subroutine call indicates that $variable should be gotten from the dictionary rather than interpreted literally. Use of $ is not the normal BasicTemplate syntax - %variable% would be more proper, but introduces a nasty parsing mess until the re engine gains balancing abilities (scheduled for perl5.6 as of this writing). The argument $_bt_dict has special meaning, and will be replaced with the hashref being used as the active substitution dictionary, thus giving your routines access to it - it will be passed in the form of a hashref, which you are free to alter during the call, so long as you keep the effects of your caching options in mind. The available formatting of arguments passed to these subroutines is any combination of: word, word, word => word, word word => "word \"word\" 'word'" word => 'word "word"' word => "word\nword", # as in: %&mysubroutine(foo,bar,snaf => 3,str => "foo bar", word => 'k"ib"o', flap => "\"ing\"")% In the first case, each word argument may contain anything but [,=>] (that is, a comma, an = or a >; yes, that is not entirely proper). If you need to use any of those characters, put the arguments in quotes. Parsing with quotations is more accurate, but depends on lookbehind assertions and is accordingly slow (the parse results are cached, so this is mostly an issue in repetitive executions rather than use of many instances in one template). When performing database queries, which may return in increments and have separate beginning and ending operations, you can use three code references in a single list reference, for beginning, middle and end. The first will be called once at the beginning, the second repeatedly until it returns false, and the third once afterward. For example: sub $number_count = 10; sub numbers_start { "Countdown, kinda like BASIC: " } sub numbers_list { $number_count-- } sub numbers_end { "\"blastoff. whee.\"" } my %ov = ( numbers => [ \&numbers_start, \&numbers_list, \&numbers_end ] ); $bt = Text::BasicTemplate->new(); $ss = '%numbers%'; print $bt->parse(\$ss,\%ov); This would call &numbers_start and insert the result, then call and insert &numbers_list until it $number_count reached zero, then call &numbers_end once and insert that. This may easily be applied, for example, to an execute, fetch, fetch, fetch, ..., finish sequence in DBI. If you need only part of these three functions (e.g. a routine that does not need a finish function), you can pass any one as an empty code reference (e.g. \ sub { }). The real use of subroutine references becomes apparent when you need the output from a function parsed into a template of its own. As noted above in the song() example, you can pass arguments to a subroutine via the template. This extends to passing hashes, e.g. %&foo(name => value)%, in which (name,value) will be passed to the subroutine referenced as foo in the parse() dictionary. You may also pass an argument (bt_template => filename), in which case the output from the coderef will be assumed to be a hashref; this hashref will then be added to the current parse() dictionary (where duplication occurs, the hashref will take precedence) and used as the dictionary given to a recursive call of parse() on the file specified by bt_template. So... sub start { return "hello, "; } my $pcount = 0; sub getname { my @people = ( { firstname => 'John', lastname => 'Doe' }, { firstname => 'Susan', lastname => 'Smith' } ); return $people[$pcount++]; } sub end { return "Nice to see you."; } # assume that /path/hello-template contains # The Esteemed %firstname% %lastname%, Lord of All You Survey $bt = Text::BasicTemplate->new(); $ss = "Greeting: \"%&greeting(bt_template => /path/hello-template)%\""; print $bt->parse(\$ss, { greeting => [ \&start, \&getname, \&end ] }); In this instance, the return values of &start and &end will be used as-is. &getname will be called until it reaches undef (on the third call); the hashrefs returned will be parsed into two copies of /tmp/hello-template. The final output would therefore be: hello, The Esteemed John Doe, Lord of All You Survey The Esteemed Susan Smith, Lord of All You Survey Nice to see you. This has obvious usefulness in terms of taking database output and making presentable (e.g. HTML) output from it, amongst other uses. PRAGMA/PREPROCESS FUNCTIONS =========================== Some basic pragma functions are provided for use in templates. These follow the same syntactical conventions as subroutine substitutions, but correspond to programs internal to Text::BasicTemplate rather than supplied by calling code. Pragmas should not be used on untrusted templates - when templates are not trustworthy, they should be disabled by setting $object->{pragma_enable}->{name_of_pragma} to false, or more simply disabling all pragmas by setting $object->{pragma_enable} = {}. If an option pragma_enable is passed to new(), it will be taken as a substitute for the enabled list and not overridden. Individual pragmas may be added or overridden with code of your own by setting $object->{pragma_functions}->{name_of_pragma} to a CODE reference. The referenced routine should expect to be passed a list containing a reference to the Text::BasicTemplate object, a hashref to the active dictionary (which may be {}), followed by any arguments passed in the template. Pragma routines must match ^bt_, or they will not be interpreted as pragmas. Pragmas provided are as follows. Note that they follow, to a reasonable extent, the format given by the Apache 1.3 mod_include specification, with a few additions. Options in [ square brackets ] are optional. bt_include({ file | virtual }, filename, [ noparse ]) ----------------------------------------------------- Includes a file in the given location in the template. The first option specifies from where the file should be loaded, equivalent to the Apache mod_include form. file means any regular path and filename. *virtual* is interpreted as relative to $object->{include_document_root} or $ENV{DOCUMENT_ROOT} in that order of precedence; if no document root is specified, no include is done. *semisecure* is a restricted form of the file form, in which files must match \w[\w\-.]{0,254} to be included (this means, generally, that the included files must be in the working directory, unless you chdir() or something). If *noparse* is supplied, the included file will be inserted as-is without further adjustment. Otherwise it will be run through parse() as would any normal template. You should use the noparse option when including an untrusted template from a trusted one. bt_include() will only include readable regular files (that is, those passing -e, -f and -r). Note that this is suceptible to race conditions, so it does not confer any security where a race could be exploited by the usual file/symlink swapping. Examples: %&bt_include(file,templates/boxscores.html)% Includes the file, parses according to the active dictionary %&bt_include(file,orders/summary.txt,noparse)% Includes the file but without any parsing on the way %&bt_include(virtual,index.html)% Includes the file index.html from the document_root directory, with parsing. bt_include() is one the user might want to override if template files are stored in a database or other non-file mechanism. bt_exec({ cmd | cgi }, command, parse) -------------------------------------- Analogous to the Apache mod_include 'exec' directive. Executes the specified command and inserts its stdout output into the template in place of the directive. If parse is specified, this output will be handed to parse() as if it were a template file. If cmd is given, the command will be read, parsed if selected, and inserted as-is without validation on the command. If cgi is given, the output will be skipped up and including the first blank line to remove HTTP headers. bt_exec() is not secure and should not be used except with trusted templates and on trusted binaries. For this reason it is disabled by default and must be manually enabled by setting $object->{pragma_enable}->{bt_exec} true either when calling new() or subsequently. COMPATIBILITY ============= Text::BasicTemplate 2.0 is a major rewrite from v0.9.8 and previous versions. Compatibility has been preserved to a degree, enough that with compatibility mode enabled, there should be no difference in either output or calling conventions. *Backwards-compatibility mode is enabled by default in v2.0, but will be disabled in some future version, possibly without notice.* Backwards compatibility is a concern in two respects, that of template format and calling conventions. TEMPLATE FORMAT --------------- The BasicTemplate 2.0 template format is only minimally compatible with the older form. If your templates include conditionals or simple_ssi HTML-style include directives, you will need to update your templates and/or use compatibility mode. A template that uses only variable substitution (e.g. "Hello %name%") will not need compatibility mode. Compatibility mode is enabled by passing 'compatibility_mode_0x => 1' to new() (see the POD for new()). Note that compatibility mode is slower than standard mode, because of conversion overhead. The convert_template_0x_2x() function can convert a 0.x template to a 2.0 template - see the POD for that function for the details. This function can easily be placed in a script to convert your templates in place, and it is likely that such a script will be provided with Text::BasicTemplate releases. CALLING CONVENTIONS ------------------- In general, there should be no necessary change between 0.x calls and 2.x calls. All the old calls have been replaced with stubs which call the new versions. These are roughly as follows: push(), parse_push() -- replaced by parse() print(), parse_print() -- replaced by print parse() list_cache() -- replaced by list_lexicon_cache() purge_cache() -- replaced by purge_*_cache() uncache() -- replaced by purge_lexicon_cache(), purge_file_cache() USEFUL FUNCTIONS ================ new() Make a Text::BasicTemplate object. Syntax is as follows: $bt = Text::BasicTemplate->new( max_parse_recursion => 32, use_file_cache => 0, use_lexicon_cache => 1, use_scalarref_lexicon_cache => 0, use_full_cond_cache => 1, use_cond2rpn_cache => 1, use_dynroutine_arg_cache => 1, use_flock => 1, default_list_delimiter => ", ", default_hash_delimiter => ", ", default_hash_specifier => "=", default_undef_identifier => "", compatibility_mode_0x => 1, eval_subroutine_refs => 1, strip_html_comments => 0, strip_c_comments => 0, strip_cpp_comments => 0, strip_perl_comments => 0, condense_whitespace => 0, simple_ssi => 1 ); All explicit arguments to new() are optional; the values shown above are the defaults. Configuration arguments given to new() have the following meanings: *max_parse_recursion*: When performing a recursive parse() on a template, as in the case of a subroutine substitution with a bt_template parameter (see the SYNTAX section), parsing will stop if recursion goes more than this depth - the typical cause would be a template A that included a subroutine reference that used a template B, which used a C, which used A again. *use_file_cache*: Templates specified to parse() by filename are read into memory before being given to the lexer. If this option is set, the contents of the file will be cached in a hash after being read. This is largely unnecessary if (as per default) lexicon caching is enabled. Do not turn this on unless you have disabled lexicon caching, or are doing something dubious to the cache yourself. *use_lexicon_cache*: If true, the lexicon generated from an input template will be cached prior to parsing. This is the normal form of caching, and enables subsequent calls to parse() to skip over the lexical parsing of templates, generally the most expensive part of the process. *use_scalarref_lexicon_cache*: If true, the above lexicon caching applies to templates given to parse() via scalar reference, as well as by filename. This is generally fine, but if you pass the contents of multiple templates by a reference to the same scalar, you may get cache mismatching. *use_full_cond_cache*: Controls caching of the results of evaluation of conditionals. Has three settings, off (0), normal (1), and persistent (2). If set off, every conditional will be reevaluated every time it is executed (this is not very expensive unless use_cond2rpn_cache is set off also; see documentation for that option). This is necessary only if you intend to change the values in the dictionary during a parse(), as in the case of a template-referenced subroutine calling a method that changes the dictionary. This cache adds some speed; the operation normally requires O(n) where n is the number of operators in the conditional, plus the cond2rpn conversion overhead, if applicable. When use_full_cond_cache is set to 1 (on, as per normal), conditionals are cached only for the span of one parse() call; if a template-referenced routine changes the dictionary for a variable already used in a conditional, the change will have no effect until the next call to parse(). When set to 2 (persistent), the conditional cache does not expire when parse() completes a single template, and indeed will not expire at all unless you call purge_fullcond_cache() manually. This setting can be useful for fast repeated parsing of the same data into multiple templates, but is not suitable when the dictionary is changing. *use_dynroutine_arg_cache*: Subroutine substitutions in templates may be passed arguments; these arguments are parsed into a suitable list before being handed to the subroutine in question. If this is enabled, the results of that parsing will be cached to speed future use. This does not incur cache mismatches; leave enabled unless you have a good reason not to. *use_flock*: If set true, template files will be flock()ed with a LOCK_SH while being read. Otherwise, they will be read blindly. Win32 afflictees might wish to disable this; in general, leave it alone. Note that files generally will need to be read only once each if either lexicon or file caching is enabled (see above). *default_list_delimiter*: When listrefs are substituted into a template, they will be join()ed with the contents of $self->{list_delimiter}->{name} if defined, or with this default value otherwise. If you wish your listrefs contatenated with no delimiting, set this to ". Default is ', '. *default_hash_delimiter*: As above, but separates key/value pairs in hashref substitution. If %x = (y => z, x => p), this delimiter will be placed between y=z and x=p. Overridden by $self->{hash_delimiter}->{name}. Deault ', '. *default_hash_specifier*: As above, separating keys and values in hashref substitution. In the above %x, this delimiter goes between y and z, and between x and p. Overriden by $self->{hash_specifier}->{name}. Default '='. *default_undef_identifier*: When a template calls for a substitution key which is undefined in the dictionary, this value will be substituted instead. Default is ". Something obvious like '**undefined**' might be a good choice for debugging purposes. *eval_subroutine_refs*: This option enables evaluation of subroutine reference substitutions, e.g. %&myroutine()%. Generally a safe option, but you might want to disable it if parsing untrustworthy templates. *compatibility_mode_0x*: Enables compatibility with templates written for Text::BasicTemplate v0.x. See COMPATIBILITY section. *strip_html_comments*: If set true, HTML comments () will be removed from the parse results. Note that nested comments are not properly stripped. Default off. *strip_c_comments*: If true, C comments (/* ... */) will be removed from parse results. Default off. *strip_cpp_comments*: If true, C and C++ comments (/* ... */ and // ...\n) will be removed from parse results. Default off. *strip_perl_comments*: If true, perl and similar style comments (# ... \n) will be removed from parse results. Default off. *condense_whitespace*: If true, whitespace in parse results will be condensed to the first byte of each, as would be done by most web browsers. Useful for tightening bandwidth usage on HTML templates without making the input templates themselves unreadable. Default off. *simple_ssi*: If true, server-parsed HTML directives of the #include persuasion will have the file referenced in their file="" or virtual="" arguments inserted in their place. The form is . This usage is deprecated in favor of the %&bt_include()% function - see the SYNTAX section. Default off; this should not be enabled when using untrusted templates. *parse SOURCE_TEMPLATE [ OVR ]* Given a source template in SOURCE_TEMPLATE, parses that template according to the key/value hash referenced by $ovr, then returns the result. If SOURCE_TEMPLATE is given as a scalar, it will be interpreted as a filename, and the contents of that file will be read, parsed, and returned. If given as a scalar reference, it will be interpreted as a reference to a buffer containing the template (the referenced template will not be modified, and copies of the relevant parts will be used to build the lexicon). If SOURCE_TEMPLATE contains an array reference, that array will be used instead of generating a new lexicon. If use_file_template_cache is true and the source template is loaded from a file, or if use_scalarref_lexicon_cache is true and the source template is given in a scalar reference, the lexicon will be cached to accelerate future parsing of the template. If the contents of either the file or the referenced buffer changes during the lifespan of the Text::BasicTemplate object, the code will not notice - if you need to change the templates in this fashion, use *uncache()* to delete the cached lexicon. Lexicon references are not cached, since the code assumes if you make your own templates you are capable of caching them, too. For templates stored in and loaded from files, note that they will be read and parsed in core, so you probably should not try to parse templates that would occupy a significant amount of your available memory. For large seldom-used templates, also consider disabling lexicon caching or calling *uncache()* afterwards. *OVR* is a euphemism for some arbitrary combination of lists, scalar paris, hashrefs and listrefs. These should cumulatively amount to the substitution dictionary - the simple form is { x => 'y' }, in which all %x% in the template will be replaced with y. (x,y) will work also (and by extension, you may pass lists of these, or raw hashes). The dictionary is parsed once, start-to-finish, so in the event of duplicated entries, the last entry of a given name will be the only one retained. Note on backwards-compatibility: in v0.x, it was possible to pass scalars of the form "x=y". This is deprecated, and is only available if *compatibility_mode_0x* is set true. Further, as references are now legal fodder for substitutions, ("x",\%y) means that %x% will parse to the contents of %y - if %y contains part of your substitution dictionary, then the above will present an error in any case, and ("x","y",\%y) is likely what you intended. parse_range \@lexicon $start $end [ \@ov ] Parses and returns the relevant parts of the specified lexicon over the given range. This has the happy side effect of eliminating the obnoxious passing around of chunks of the lexicon. Instead one need only pass references to a single lexicon and the range over which it should be parsed. This routine does the actual work of parse(), but is really only useful internally. cond_evaluate CONDITIONAL [ \%ovr ] Evaluates the specified conditional left-to-right. At present it does not handle operators also, just boolean/scalar evaluation. identifier_evaluate $identifier \%ovr [ $type, $name ] Evaluates the specified identifier and returns its value. Literals, being of the form \d+, "[...]" and '[...]', are returned as-is (leading and trailing quotes will be removed from string literals). Identifiers of standard (no special type) form are returned as they appear in \%ovr; if those stored values are listrefs or hashrefs, they will be returned in formatted form - listrefs will be returned as a scalar delimited by the value of $self->{list_delimiter}->{name}, hashes will be mapped into a scalar using $self->{hash_specifier}->{name} and $self->{hash_delimiter}->{name}, which three have the form ", ", "=" and ", " respectively by default. Identifiers of the form $name will be checked against the environment variable of the same name, and if present, that value will be returned, otherwise undef will be returned. Identififers of the form &name will be returned according to those entries in \%ovr of the form &name - this is used to provide a separate namespace for substitutions, e.g. for CGI parameters. Identifiers of the form !name will be evaluated according to the return value(s) from whatever stored procedure(s) have been registered under that name, if any. See `store_dynroutine' for details. evaluate_dynroutine $name, $args, \%ovr Evalutes a routine referenced by a template. The general form gives the name of the routine in $name (if no such named routine is available, returns undef), any arguments as a scalar $args, and the key-sub list in $ovr. $args should be given as a scalar - it will be parsed in parse_dynroutine_args and the result cached against future use. parse_dynroutine_args $argstr Pulls apart the argument string passed to a template-referenced dynamic routine, and returns a listref for it. Format tolerance is only minimally clever. The formats tolerated are, in any combination: word, word, word => word, word word => "word \"word\" 'word'" word => 'word "word"' word => "word\nword", In the first case, each word argument may contain anything but [,=>'"] (that is, ', ", =, or >; yes, that is not entirely proper). If you need to use any of those characters, put the arguments in quotes. Parsing with quotations is more accurate, but depends on lookbehind assertions and is accordingly slow (the parse results are cached, so this is mostly an issue in repetitive executions rather than use of many instances in one template). evaluate_pragma $name, $args, \%ovr is_identifier \$candidate Takes a reference to a scalar containing a potential identifier. In a scalar context, returns 1 or 0. In a list context, returns (type,name) where type is one of the identififer type designators (&, !, $, etc) and name is the remainder of the identifier. lex \$src Splits the specified source buffer into a series of tokens, returns a listref to the resulting lexicon. See *ABOUT* for the details. load_from_file $filename Loads a template from the specified file. If use_file_cache is true, the file will be stored in the file cache (not necessary if caching is enabled for lexicons). This code is very trusting concerning its filename - the only check performed is to strip leading <, >, | and + signs to try to ensure that the filehandle obtained is read-only. Trailing pipes will be left alone, so that "/path/to/binary|" may use the output from 'binary'. bt_exec dump_lexicon \@lexicon [ $start_pos [ $end_pos ] ] Returns a dump of the given lexicon. Principally used for debugging the module, or if you need to optimize templates to save lexical storage. If $start_pos/$end_pos are given, only that range of the lexical array is dumped. dump_stack \@stack Dumps the contents of a conditional-eval stack, which consists of a list of listrefs containing [ type, value ], type being one of the lexeme_types, value being either the identififer or an operator, depending on the type. list_lexicon_cache Lists the lexicons cached for files/scalars/etc. list_file_cache Lists the files cached in the file cache. Empty unless use_file_cache is true. list_cond2rpn_cache Lists the conditional-to-RPN conversion cache. Empty if *use_cond2rpn_cache* is false. list_fullcond_cache Lists the contents of the conditional evaluation cache. Empty unless *use_full_cond_cache* is set true. taint_enabled Tries to work out if taint checking is enabled, so that the right things can be enabled/disabled by new(). is_tainted SCALAR Returns true if taint checking is enabled and the specified variable is tainted. debug DEBUGLEVEL Activates debugging output. purge_lexicon_cache purge_cond2rpn_cache purge_fullcond_cache purge_file_cache Purges the given cache. list_cache Compatibility function for BasicTemplate 0.x; synonym for list_lexicon_cache push, parse_push Compatibility functions for BasicTemplate 0.x; synonym for parse. print, parse_print Compatibility functions for BasicTempltae 0.x purge_cache Compatibility function for BasicTemplate 0.x; purges all applicable caches. uncache FILE Compatibility function for BasicTemplate 0.x; purges the specified file from the file and lexicon caches. convert_template_0x_2x $buffer Backwards-compatibility function for BasicTemplate 0.x; converts a template constructed for v0.x to v2.x. Used internally for conversions on-the-fly in backwards-compatible mode. Note that this method will have no effect unless the 0.x template contains conditionals - simple %key% substitutions are the same in both versions. HISTORY ======= 2.004: Fixed a dumb oversight in test suite where valid comparison strings assumed that the iteration order in a hash would be consistent and predictable. Passes make-test under perl5.6 now. 2.0: Major rewrite. Introduced lexical parsing, nested conditionals, list/hash formatting, subroutine references, operator evaluation and much other related stuff. 0.9.8: Added subroutine-reference parsing. This makes it possible to bind keys to subroutines which will be called (once per template) when needed; this can make things quicker if the template-specific informational requirements may not be easily predicted in advance. 0.9.7: Made stripping of lingering keys optional (default off); it was causing problems with URI-encoded substitutions, and in retrospect probably was not a good idea anyway. Thanks to Ian Baker for the bug report. 0.9.6.1: Fixed stupid idiotic bug caused by overzealous optimization (some things were not meant to be done with references - setting cache scalars, for iinstance). Renamed from ParsePrint to BasicTemplate for submission to CPAN. Fixed oversight wherein files inserted via simple_ssi #includes were having keys stripped, but not parsed first. First fully public release. Hooray... 0.9.6: Rewrote argument handling in constructor the same way; deprecated old style arg passage. 0.9.5: Rewrote argument handling in parse_push to handle arbitrary combinations of different arg types. 0.9.4.1: Fixed nasty bug that set the lvalue in comparison to the name of the entitity lvalue, not the value thereof. 0.9.4: Lots of optimizations. Inlined eval_conditional(), introduced caching of condititionals (parse-once, print repeatedly), other such changes. Approximately doubled output speed to about 3100 conditionals/sec on my i686-200 Linux box. 0.9.3: First stable, releaseable version. Much documentation. AUTHOR ====== Text::BasicTemplate is by Devin Carraway , originally written for Sonoma.Net in 1996. Maintained until v0.9.5 as ParsePrint, then Text::ParsePrint, then renamed for CPAN upload to Text::BasicTemplate. Assorted further assistance and debugging rendered by Ian Baker and Eric Eisenhart . COPYRIGHT ========= Copyright (c) 1996-1997 by Devin Carraway and Sonoma.Net. Copyright (c) 1997-1999 by Devin Carraway. Released under terms of the Perl Artistic License.