You are viewing the version of this documentation from Perl 5.24.3. View the latest version

CONTENTS

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 XML tag.

	($extracted, $remainder) = extract_tagged($text);


 # Extract the initial substring of $text that is bounded by
 # a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> 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('<HEAD>','</HEAD>');

($extracted, $remainder) = $extract_head->($text);

DESCRIPTION

The various extract_... subroutines may be used to extract a delimited substring, possibly after skipping a specified prefix string. By default, that prefix is optional whitespace (/\s*/), but you can change it to whatever you wish (see below).

The substring to be extracted must appear at the current pos location of the string's variable (or at index zero, if no pos position is defined). In other words, the extract_... subroutines don't extract the first occurrence of a substring anywhere in a string (like an unanchored regex would). Rather, they extract an occurrence of the substring appearing immediately at the current matching position in the string (like a \G-anchored regex would).

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 undef 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, undef 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 '.*?(?=<H1>)' to skip everything up to the first <H1> tag. Such a prefix pattern will only succeed if the <H1> 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).*?(?=<H1>)'

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" 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 = '<A HREF=">>>>">link</A>';

then

@result = extract_bracketed( $text, '<">' );

returns:

( '<A HREF=">>>>">', 'link</A>', "" )

as expected. Without the specification of " as an embedded quoter:

@result = extract_bracketed( $text, '<>' );

the result would be:

( '<A HREF=">', '>>>">link</A>', "" )

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, '<q>' );

would correctly match something like this:

$text = '<leftop: conj /and/ conj>';

See also: "extract_quotelike" and "extract_codeblock".

extract_variable

extract_variable extracts any valid Perl variable or variable-involved expression, including scalars, arrays, hashes, array accesses, hash look-ups, method calls through objects, subroutine calls through subroutine references, etc.

The subroutine takes up to two 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 a prefix (which is to be skipped). If omitted, optional whitespace is skipped.

On success in a list context, an array of 3 elements is returned. The elements are:

[0]

the extracted variable, or variablish expression

[1]

the remainder of the input text,

[2]

the prefix substring (if any),

On failure, all of these values (except the remaining text) are undef.

In a scalar context, extract_variable returns just the complete substring that matched a variablish expression. 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.

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 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, '<A>', '</A>', undef, {reject => ['<A>']} );
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" 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 <reject> 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:

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)) 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 "<QLL>"

        do { $_ = join '<QLL>', (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),