Text::Balanced(3perl)
π¦ Text::Balanced π¦
okay so this is Text::Balanced(3perl) from the Perl Programmers Reference Guide, and bestie, it's about to become your whole personality. no cap. π
πΈ NAME πΈ
Text::Balanced β extract delimited text sequences from strings. that's it, that's the vibe. π
β¨ 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.
$extract_head = gen_extract_tagged('<HEAD>','</HEAD>');
($extracted, $remainder) = $extract_head->($text);
π DESCRIPTION π
so the whole family of extract_... subroutines is here to pull a delimited substring out of a string for you β sometimes after it skips over a prefix string you told it about. by default that prefix is just optional whitespace, aka /\s*/, but you can swap it for literally whatever you want (more on that below π).
the substring you're grabbing has to sit at the current pos spot of the string's variable β or at index zero if there's no pos position defined at all. and this is the part people get wrong: the extract_... subs do not hunt down the first occurrence of a substring anywhere in the string like some unanchored regex would. no ma'am. they grab the occurrence that's sitting right at the current matching position of the string β exactly like a \G-anchored regex behaves. β¨
π«Ά General Behaviour in List Contexts π«Ά
in list context, all the subroutines hand back a list, and the first three elements of that list are always these:
- [0] β the extracted string, delimiters and all. if the extraction flops,
undefcomes back instead. π - [1] β the remainder of the input string, i.e. all the characters that come after the extracted string. on failure you get the entire string back, no loss.
- [2] β the skipped prefix, i.e. the characters that came before the extracted string. on failure,
undef. π
note that in list context, the contents of the original input text (that's the first argument) are not modified in any way. she's untouched. she's safe.
but β and this is the twist β if the input text was passed in as a variable, that variable's pos value gets updated to point at the first character after the extracted text. which means in list context these subs can be used basically like regular expressions. iconic behaviour, honestly:
while ( $next = (extract_quotelike($text))[0] )
{
# process next quote-like (in $next)
}
π General Behaviour in Scalar and Void Contexts π
in scalar context, the extracted string is returned β and it has already been removed from the input text. so this next bit also processes every quote-like operation, except it actually deletes them out of $text as it goes:
while ( $next = extract_quotelike($text) )
{
# process next quote-like (in $next)
}
heads up bestie: if the input text is a read-only string (like a literal), no attempt is made to remove the extracted text. can't delete what's frozen, and she doesn't even try. π
in void context, the extraction subroutines behave exactly the same as in scalar context β except, obviously, that the extracted substring never gets returned to you. same energy, just no gift at the end.
π A Note About Prefixes π
prefix patterns are matched with no trailing modifiers (/gimsox etc.). and this will bite you if you're out here expecting a prefix like '.*?(?=<H1>)' to skip everything up to the first <H1> tag. that prefix pattern only succeeds if the <H1> tag is sitting on the current line, because . normally doesn't match newlines. rude, but true.
to get around this limitation, you need to turn on /s matching inside the prefix pattern itself, using the (?s) directive: '(?s).*?(?=<H1>)' π
π Functions π
π 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 grab a single-quote-delimited string, the code you'd typically be writing is:
($remainder = $text) =~ s/\A('(\\.|[^'])*')//s;
$extracted = $1;
but with extract_delimited it simplifies down to just:
($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's appropriately delimited. if the delimiter string has multiple characters, the first one encountered in the text is the one taken to delimit the substring. the third argument is a prefix pattern that gets skipped (but it must be present! before the substring gets extracted). and the final argument specifies the escape character to use for each delimiter.
all arguments are optional, bestie. here's the tea:
- if the escape characters aren't specified, every delimiter is escaped with a backslash,
"\". - if the prefix isn't specified, the pattern
'\s*'β optional whitespace β is used. - if the delimiter set isn't specified either, the set
"/["'`]/"is used. - and if the text to be processed isn't specified either?
$_gets used. she's always there for you. π«Ά
in list context, extract_delimited returns an array of three elements: the extracted substring (including the surrounding delimiters), the remainder of the text, and the skipped prefix (if any). if no suitable delimited substring gets found, then 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 scalar context, just the extracted substring comes back. in void context, the extracted substring (and any prefix) are simply removed from the beginning of the first argument. gone. bye. π
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];
okay so important: that last example is not the same as deleting the first quote-like pattern. watch. if $text contained the string:
"if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }"
then after the deletion it would contain:
"if ('.$UNIXCMD/s) { $cmd = $1; }"
and 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. same rules as before β a missing prefix defaults to optional whitespace, and a missing text defaults to $_. but a missing delimiter specifier defaults to '{}()[]<>' (see below for what that means).
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 (again, see below).
a "delimiter bracket" is a bracket in the list of delimiters you pass as extract_bracketed's second argument. you specify delimiter brackets by giving either the left or the right (or both!) versions of the bracket(s) you want. note that the order you specify two or more delimiter brackets in is not significant. she does not care. π§
a "balanced-bracket-delimited substring" is a substring bounded by matched brackets, such that any other (left or right) delimiter bracket inside the substring is also matched by an opposite (right or left) delimiter bracket at the same level of nesting. and any type of bracket that's not in the delimiter list? treated as an ordinary character. no drama, no special treatment.
in other words: each type of bracket you specified as a delimiter must be balanced and correctly nested inside the substring, and any other kind of ("non-delimiter") bracket in there is just ignored. periodt.
for example, given the string:
$text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }";
then a call to extract_bracketed in a list context:
okay so back to the brackets, bestie π
we were literally mid-extract_bracketed and the receipts are wild. so if $text is that messy string from before, then
@result = extract_bracketed( $text, '{}' );
would return:
( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" )
because both sets of '{..}' brackets are properly nested and evenly balanced. (also, vibes note: in a scalar context you just get the first element of the array back. In a void context, $text would be replaced by an empty string. so like, it's gone gone.)
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. slay.
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. so it's giving "no harm no foul".)
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). fr fr β if you don't put a quote char in the list, Perl is not gonna read your mind about it.
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 π β gimme that 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. like, if it smells like a variable, she's grabbing it.
The subroutine takes up to two optional arguments:
- A string to be processed (
$_if the string is omitted or"undef") - 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. poof. gone. π¨
extract_tagged π¦ β tags but make it balanced
"extract_tagged" extracts and segments text between (balanced) specified tags.
The subroutine takes up to five optional arguments:
- A string to be processed (
$_if the string is omitted or"undef") - A string specifying a pattern (i.e. regex) 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. - 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}}". - A string specifying a pattern to be matched as a prefix (which is to be skipped). If omitted, optional whitespace is skipped.
- 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 to 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 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 π β the pre-compiled glow-up
"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).
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". twice!! the speed!! bestie, that's a whole second function for free. π₯
extract_quotelike π
β all the quotes, all of them
"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. she really said "I know every quote syntax and I'm not scared of any of them."
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:
so picture this regex, right:
'm /
(?i) # CASE INSENSITIVE
[a-z_] # LEADING ALPHABETIC/UNDERSCORE
[a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS
/x'
bestie⦠it gets extracted as if it were literally this:
'm /
(?i) # CASE INSENSITIVE
[a-z_] # LEADING ALPHABETIC/'
see what happened?? that / hiding inside the comment got clocked as the closing delimiter π and this behaviour is identical to that of the actual compiler. so like, not a bug, that's just the vibe. periodt.
extract_quotelike takes two arguments: the text to be processed, and a prefix to be matched at the very beginning of the text. No prefix specified? optional whitespace is the default. No text given? $_ gets pulled in, obviously. π
In a list context, you get back an array of 11 elements. here's the tea, one by one:
- [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 every field marked "(if any)" β on success the default value is an empty string. on failure, all of these values (except the remaining text) are undef. so like, check your returns, girlies. π
In a scalar context, extract_quotelike returns just the complete substring that matched a quotelike operation (or undef on failure, you already know). And in a scalar or void context, the input text has that same substring (plus any specified prefix) removed from it. poof. gone. β¨
Examples, because we love receipts:
# 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 (the here-doc era) π«Ά
okay so extract_quotelike can successfully extract "here documents" from an input string, but there's a caveat in list contexts and you need to know about it. π
Unlike other types of quote-like literals, a here document is rarely a contiguous substring. like, it's giving scattered. typical here-doc code might look like:
<<'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. so the two separate pieces of the here document got successfully extracted and concatenated. slay. π
In a list context though, extract_quotelike would return this 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. π not the skipped content bestie!!
To dodge this problem, when it encounters a here document whilst extracting from a modifiable string, extract_quotelike silently rearranges the string into an equivalent piece of Perl:
<<'EOMSG'
This is the message.
EOMSG
|| die;
exit;
in which the here document is actually 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 preventextract_quotelikefrom mucking about with the input in this way (this is the only case where a list-contextextract_quotelikedoes so, so like, don't panic), 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. basically it's extract_bracketed and extract_quotelike in a little trench coat. they're a combo. π§
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 lets the outermost delimiter brackets be specified separately (more on that below, iykyk), and a fifth parameter used only by Parse::RecDescent.
- Omitting the first argument (input text)? process
$_instead. - Omitting the second argument (delimiter brackets)? only
'{'is used. - Omitting the third argument (prefix argument)? optional whitespace at the start.
- Omitting the fourth argument (outermost delimiter brackets)? the value of the second argument is used for the outermost delimiters.
once the prefix and the outermost opening delimiter bracket have been recognized, code blocks get extracted by stepping through the input text and trying the following alternatives in sequence:
- 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.
- Try to match a quote or quotelike operator. If found, call
extract_quoteliketo eat it. Ifextract_quotelikefails, return the error it returned. Otherwise go back to step 1. - Try to match an opening delimiter bracket. If found, call
extract_codeblockrecursively to eat the embedded block. If the recursive call fails, return an error. Otherwise, go back to step 1. - Unconditionally match a bareword or any other single character, and then go back to step 1.
Examples, bestie, take notes:
# 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 <defer:...> directive. like so:
sentence: subject verb object
<defer: {$::theVerb = $item{verb}} >
Parse::RecDescent uses extract_codeblock($text, '{}<>') to extract the code within the <defer:...> directive, but there's a problem. π
A deferred action like this:
<defer: {if ($count>10) {$count--}} >
will be incorrectly parsed as:
<defer: {if ($count>
because the "less than" operator is interpreted as a closing delimiter. the audacity of that > honestly.
But, by extracting the directive using extract_codeblock($text, '{}', undef, '<>') the '>' character is only treated as a delimiter at the outermost level of the code block, so the directive is parsed correctly. fixed. healed. iconic. π
πΈ 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_multiplereturns an array of substrings of the original string, as extracted by the specified extractors. - In a scalar context,
extract_multiplereturns 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_multiplestarts at the currentposof the string, and sets thatposappropriately after it matches.
Hence, the aim 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. so basically extract_multiple is a generalized form of Perl's split subroutine. it's split's cooler older sister. π
The subroutine takes up to four optional arguments:
- A string to be processed (
$_if the string is omitted orundef) - 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 (orundef) the list:
and this lil default squad:
[
sub { extract_variable($_[0], '') },
sub { extract_quotelike($_[0],'') },
sub { extract_codeblock($_[0],'{}','') },
]
is what gets used. periodt. β¨
- A 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). π
- 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. it's giving assembly line but make it perl π
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. It may optionally also return two further arguments: a string representing the text left after extraction (like $' for a pattern match), and a string representing any prefix skipped before the extraction (like $`` in a pattern match). Note that this is designed to facilitate the use of other Text::Balanced subroutines with extract_multiple`. Note too that the value returned by an extractor subroutine need not bear any relationship to the corresponding substring of the original text (see examples below). no cap, it can be anything bestie π
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. $&). iconic regex behavior tbh π
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. it's giving 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 discarded). lowkey brutal but that's the vibe π
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:
$csv_text = "a,'x b',c";
@fields = extract_multiple($csv_text,
[
sub { extract_delimited($_[0],q{'"}) },
qr/([^,]+)/,
],
undef,1);
# @fields is now ('a', "'x b'", 'c')
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). bestie just remove it and slay π
β¨ "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. no cap, it handles the escaping for you π«Ά
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.
π "delimited_pat" π
Note that gen_delimited_pat was previously called delimited_pat. That name may still be used, but is now deprecated.
π DIAGNOSTICS π
okay bestie, listen. every single one of these functions fails the exact same way, and it's giving very consistent, very demure:
- In a list context, every function returns
(undef,$original_text)when it fails. That's it. That's the whole failure vibe. π« - In a scalar context, failure is just plain old
undef, and heads up β in that case the input text is not modified in any way. Untouched. Pristine. No cap. - And on failure in any context, the
$@variable gets set. Yes really.
So how do you interrogate $@? Obsessed you asked:
$@->{error}gives you back one of the error diagnostics listed below. queen behavior.$@->{pos}gives you the offset into the original string at which the error was detected β although, fair warning, not necessarily where it actually occurred. it's giving "approximately there". π- If you just print
$@directly, you get the error message with the offset appended. easy. - On success,
$@is guaranteed to beundef. slay.
π¨ The available diagnostics π¨
"Did not find a suitable bracket: "%s""β the delimiter you handed toextract_bracketedwas not one of'()[]<>{}'. it's not like the other girls."Did not find prefix: /%s/"β you specified a non-optional prefix and it simply wasn't there at the start of the text. gone. missing. π"Did not find opening bracket after prefix: "%s""βextract_bracketedorextract_codeblockwas expecting a particular kind of bracket at the start of the text and did not find it."No quotelike operator found after prefix: "%s""βextract_quotelikedidn't find one of the quotelike operatorsq,qq,qw,qx,s,troryat the start of the substring it was extracting."Unmatched closing bracket: "%c""βextract_bracketed,extract_quotelikeorextract_codeblockhit a closing bracket where none was expected. rude honestly."Unmatched opening bracket(s): "%s""βextract_bracketed,extract_quotelikeorextract_codeblockran out of characters in the text before closing one or more levels of nested brackets. the text just ended. mid-nesting. embarrassing."Unmatched embedded quote (%s)"βextract_bracketedtried to match an embedded quoted substring but could not find a closing quote to match it."Did not find closing delimiter to match '%s'"βextract_quotelikewas unable to find a closing delimiter to match the one that opened the quote-like operation. the quote is open. it stays open. forever. π¦"Mismatched closing bracket: expected "%c" but found "%s""βextract_bracketed,extract_quotelikeorextract_codeblockfound a valid bracket delimiter, but it was the wrong species. this usually means a nesting error, but it may also indicate incorrect quoting or escaping. so check your escapes bestie."No block delimiter found after quotelike "%s""βextract_quotelikeorextract_codeblockfound one of the quotelike operatorsq,qq,qw,qx,s,trorywithout a suitable block after it."Did not find leading dereferencer"βextract_variablewas expecting one of'$','@', or'%'at the start of a variable and found none of them."Bad identifier after dereferencer"βextract_variabledid find 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_codeblockfailed 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 specified as only to be used as an outermost bracket. rules are rules."Missing second block for quotelike "%s""βextract_codeblockorextract_quotelikefound one of the quotelike operatorss,troryfollowed by only one block. where's the other one. π§"No match found for opening bracket"βextract_codeblockfailed to find a closing bracket to match the outermost opening bracket."Did not find opening tag: /%s/"βextract_taggeddid not find a suitable opening tag (after any specified prefix was removed)."Unable to construct closing tag to match: /%s/"βextract_taggedmatched 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 that closing tag, almost certainly because the opening tag did not start with a bracket of some kind. almost certainly, bestie."Found invalid nested tag: %s"βextract_taggedfound a nested tag that appeared in the"reject"list (and the failure mode was not"MAX"or"PARA")."Found unbalanced nested tag: %s"βextract_taggedfound 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_taggedreached 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").
π EXPORTS π
these are the symbols that are β or can be β exported by this module:
Default Exports
None. nothing. zero. the default is no free gifts. iconic restraint honestly. π
Optional Exports
extract_delimited, extract_bracketed, extract_quotelike, extract_codeblock, extract_variable, extract_tagged, extract_multiple, gen_delimited_pat, gen_extract_tagged, delimited_pat.
Export Tags
:ALLβextract_delimited,extract_bracketed,extract_quotelike,extract_codeblock,extract_variable,extract_tagged,extract_multiple,gen_delimited_pat,gen_extract_tagged,delimited_pat. that's the whole squad, all at once. take everything. π
π KNOWN BUGS π
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Text-Balanced>.
(translation: the currently-active ones live right there, go look, iykyk)
π«Ά FEEDBACK π«Ά
Patches, bug reports, suggestions or any other feedback is welcome. genuinely. we want it. π₯Ή
- Patches can be sent as GitHub pull requests at <https://github.com/steve-m-hay/Text-Balanced/pulls>.
- Bug reports and suggestions can be made on the CPAN Request Tracker at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Text-Balanced>.
- Currently active requests on the CPAN Request Tracker can be viewed at <https://rt.cpan.org/Public/Dist/Display.html?Queue=Text-Balanced>.
- Please test this distribution. See CPAN Testers at <https://www.cpantesters.org/> for details of how to get involved.
- Previous test results on CPAN Testers can be viewed at <https://www.cpantesters.org/distro/T/Text-Balanced.html> and <https://fast2-matrix.cpantesters.org/?dist=Text-Balanced>.
π¦ AVAILABILITY π¦
The latest version of this module is available from CPAN (see "CPAN" in perlmodlib for details) at
<https://metacpan.org/release/Text-Balanced> or
<https://www.cpan.org/authors/id/S/SH/SHAY/> or
<https://www.cpan.org/modules/by-module/Text/>.
The latest source code is available from GitHub at <https://github.com/steve-m-hay/Text-Balanced>.
π οΈ INSTALLATION π οΈ
See the INSTALL file.
π AUTHOR π
Damian Conway <damian@conway.org <mailto:damian@conway.org>>.
Steve Hay <shay@cpan.org <mailto:shay@cpan.org>> is now maintaining Text::Balanced as of version 2.03. passing the torch, and honestly? the torch is being carried. π₯
Β©οΈ COPYRIGHT Β©οΈ
Copyright (C) 1997-2001 Damian Conway. All rights reserved.
Copyright (C) 2009 Adam Kennedy.
Copyright (C) 2015, 2020, 2022 Steve Hay and other contributors. All rights reserved.
π LICENCE π
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the LICENCE file.
π’ VERSION π’
Version 2.07
π DATE π
08 Aug 2025
π°οΈ HISTORY π°οΈ
See the Changes file.
and that's the whole page bestie!! πβ¨ this one's from Text::Balanced(3perl), running under perl v5.44.0, dated 2026-10-17 β go balance some text, you absolute main character ππ¦πΈ
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms