{
    "content": [
        {
            "type": "text",
            "text": "# Text::Balanced (perldoc)\n\n**Summary:** Text::Balanced - Extract delimited text sequences from strings.\n\n**Synopsis:** use Text::Balanced qw (\nextractdelimited\nextractbracketed\nextractquotelike\nextractcodeblock\nextractvariable\nextracttagged\nextractmultiple\ngendelimitedpat\ngenextracttagged\n);\n# Extract the initial substring of $text that is delimited by\n# two (unescaped) instances of the first character in $delim.\n($extracted, $remainder) = extractdelimited($text,$delim);\n# Extract the initial substring of $text that is bracketed\n# with a delimiter(s) specified by $delim (where the string\n# in $delim contains one or more of '(){}[]<>').\n($extracted, $remainder) = extractbracketed($text,$delim);\n# Extract the initial substring of $text that is bounded by\n# an XML tag.\n($extracted, $remainder) = extracttagged($text);\n# Extract the initial substring of $text that is bounded by\n# a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags\n($extracted, $remainder) =\nextracttagged($text,\"BEGIN\",\"END\",undef,{bad=>[\"BEGIN\"]});\n# Extract the initial substring of $text that represents a\n# Perl \"quote or quote-like operation\"\n($extracted, $remainder) = extractquotelike($text);\n# Extract the initial substring of $text that represents a block\n# of Perl code, bracketed by any of character(s) specified by $delim\n# (where the string $delim contains one or more of '(){}[]<>').\n($extracted, $remainder) = extractcodeblock($text,$delim);\n# Extract the initial substrings of $text that would be extracted by\n# one or more sequential applications of the specified functions\n# or regular expressions\n@extracted = extractmultiple($text,\n[ \\&extractbracketed,\n\\&extractquotelike,\n\\&someotherextractorsub,\nqr/[xyz]*/,\n'literal',\n]);\n# Create a string representing an optimized pattern (a la Friedl)\n# that matches a substring delimited by any of the specified characters\n# (in this case: any type of quote or a slash)\n$patstring = gendelimitedpat(q{'\"`/});\n# Generate a reference to an anonymous sub that is just like extracttagged\n# but pre-compiled and optimized for a specific pair of tags, and\n# consequently much faster (i.e. 3 times faster). It uses qr// for better\n# performance on repeated calls.\n$extracthead = genextracttagged('<HEAD>','</HEAD>');\n($extracted, $remainder) = $extracthead->($text);\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (71 lines)\n- **DESCRIPTION** (10 lines) — 3 subsections\n  - General Behaviour in List Contexts (24 lines)\n  - General Behaviour in Scalar and Void Contexts (24 lines)\n  - Functions (721 lines)\n- **DIAGNOSTICS** (96 lines)\n- **EXPORTS** (17 lines)\n- **KNOWN BUGS** (2 lines)\n- **FEEDBACK** (20 lines)\n- **AVAILABILITY** (12 lines)\n- **INSTALLATION** (2 lines)\n- **AUTHOR** (5 lines)\n- **COPYRIGHT** (6 lines)\n- **LICENCE** (4 lines)\n- **VERSION** (2 lines)\n- **DATE** (2 lines)\n- **HISTORY** (2 lines)\n\n## Full Content\n\n### NAME\n\nText::Balanced - Extract delimited text sequences from strings.\n\n### SYNOPSIS\n\nuse Text::Balanced qw (\nextractdelimited\nextractbracketed\nextractquotelike\nextractcodeblock\nextractvariable\nextracttagged\nextractmultiple\ngendelimitedpat\ngenextracttagged\n);\n\n# Extract the initial substring of $text that is delimited by\n# two (unescaped) instances of the first character in $delim.\n\n($extracted, $remainder) = extractdelimited($text,$delim);\n\n# Extract the initial substring of $text that is bracketed\n# with a delimiter(s) specified by $delim (where the string\n# in $delim contains one or more of '(){}[]<>').\n\n($extracted, $remainder) = extractbracketed($text,$delim);\n\n# Extract the initial substring of $text that is bounded by\n# an XML tag.\n\n($extracted, $remainder) = extracttagged($text);\n\n# Extract the initial substring of $text that is bounded by\n# a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags\n\n($extracted, $remainder) =\nextracttagged($text,\"BEGIN\",\"END\",undef,{bad=>[\"BEGIN\"]});\n\n# Extract the initial substring of $text that represents a\n# Perl \"quote or quote-like operation\"\n\n($extracted, $remainder) = extractquotelike($text);\n\n# Extract the initial substring of $text that represents a block\n# of Perl code, bracketed by any of character(s) specified by $delim\n# (where the string $delim contains one or more of '(){}[]<>').\n\n($extracted, $remainder) = extractcodeblock($text,$delim);\n\n# Extract the initial substrings of $text that would be extracted by\n# one or more sequential applications of the specified functions\n# or regular expressions\n\n@extracted = extractmultiple($text,\n[ \\&extractbracketed,\n\\&extractquotelike,\n\\&someotherextractorsub,\nqr/[xyz]*/,\n'literal',\n]);\n\n# Create a string representing an optimized pattern (a la Friedl)\n# that matches a substring delimited by any of the specified characters\n# (in this case: any type of quote or a slash)\n\n$patstring = gendelimitedpat(q{'\"`/});\n\n# Generate a reference to an anonymous sub that is just like extracttagged\n# but pre-compiled and optimized for a specific pair of tags, and\n# consequently much faster (i.e. 3 times faster). It uses qr// for better\n# performance on repeated calls.\n\n$extracthead = genextracttagged('<HEAD>','</HEAD>');\n($extracted, $remainder) = $extracthead->($text);\n\n### DESCRIPTION\n\nThe various \"extract...\" subroutines may be used to extract a delimited substring, possibly\nafter skipping a specified prefix string. By default, that prefix is optional whitespace\n(\"/\\s*/\"), but you can change it to whatever you wish (see below).\n\nThe substring to be extracted must appear at the current \"pos\" location of the string's variable\n(or at index zero, if no \"pos\" position is defined). In other words, the \"extract...\"\nsubroutines *don't* extract the first occurrence of a substring anywhere in a string (like an\nunanchored regex would). Rather, they extract an occurrence of the substring appearing\nimmediately at the current matching position in the string (like a \"\\G\"-anchored regex would).\n\n#### General Behaviour in List Contexts\n\nIn a list context, all the subroutines return a list, the first three elements of which are\nalways:\n\n[0] The extracted string, including the specified delimiters. If the extraction fails \"undef\" is\nreturned.\n\n[1] The remainder of the input string (i.e. the characters after the extracted string). On\nfailure, the entire string is returned.\n\n[2] The skipped prefix (i.e. the characters before the extracted string). On failure, \"undef\" is\nreturned.\n\nNote that in a list context, the contents of the original input text (the first argument) are\nnot modified in any way.\n\nHowever, if the input text was passed in a variable, that variable's \"pos\" value is updated to\npoint at the first character after the extracted text. That means that in a list context the\nvarious subroutines can be used much like regular expressions. For example:\n\nwhile ( $next = (extractquotelike($text))[0] )\n{\n# process next quote-like (in $next)\n}\n\n#### General Behaviour in Scalar and Void Contexts\n\nIn a scalar context, the extracted string is returned, having first been removed from the input\ntext. Thus, the following code also processes each quote-like operation, but actually removes\nthem from $text:\n\nwhile ( $next = extractquotelike($text) )\n{\n# process next quote-like (in $next)\n}\n\nNote that if the input text is a read-only string (i.e. a literal), no attempt is made to remove\nthe extracted text.\n\nIn a void context the behaviour of the extraction subroutines is exactly the same as in a scalar\ncontext, except (of course) that the extracted substring is not returned.\n\nA Note About Prefixes\nPrefix patterns are matched without any trailing modifiers (\"/gimsox\" etc.) This can bite you if\nyou're expecting a prefix specification like '.*?(?=<H1>)' to skip everything up to the first\n<H1> tag. Such a prefix pattern will only succeed if the <H1> tag is on the current line, since\n. normally doesn't match newlines.\n\nTo overcome this limitation, you need to turn on /s matching within the prefix pattern, using\nthe \"(?s)\" directive: '(?s).*?(?=<H1>)'\n\n#### Functions\n\n\"extractdelimited\"\nThe \"extractdelimited\" function formalizes the common idiom of extracting a\nsingle-character-delimited substring from the start of a string. For example, to extract a\nsingle-quote delimited string, the following code is typically used:\n\n($remainder = $text) =~ s/\\A('(\\\\.|[^'])*')//s;\n$extracted = $1;\n\nbut with \"extractdelimited\" it can be simplified to:\n\n($extracted,$remainder) = extractdelimited($text, \"'\");\n\n\"extractdelimited\" takes up to four scalars (the input text, the delimiters, a prefix\npattern to be skipped, and any escape characters) and extracts the initial substring of the\ntext that is appropriately delimited. If the delimiter string has multiple characters, the\nfirst one encountered in the text is taken to delimit the substring. The third argument\nspecifies a prefix pattern that is to be skipped (but must be present!) before the substring\nis extracted. The final argument specifies the escape character to be used for each\ndelimiter.\n\nAll arguments are optional. If the escape characters are not specified, every delimiter is\nescaped with a backslash (\"\\\"). If the prefix is not specified, the pattern '\\s*' - optional\nwhitespace - is used. If the delimiter set is also not specified, the set \"/[\"'`]/\" is used.\nIf the text to be processed is not specified either, $ is used.\n\nIn list context, \"extractdelimited\" returns a array of three elements, the extracted\nsubstring (*including the surrounding delimiters*), the remainder of the text, and the\nskipped prefix (if any). If a suitable delimited substring is not found, the first element\nof the array is the empty string, the second is the complete original text, and the prefix\nreturned in the third element is an empty string.\n\nIn a scalar context, just the extracted substring is returned. In a void context, the\nextracted substring (and any prefix) are simply removed from the beginning of the first\nargument.\n\nExamples:\n\n# Remove a single-quoted substring from the very beginning of $text:\n\n$substring = extractdelimited($text, \"'\", '');\n\n# Remove a single-quoted Pascalish substring (i.e. one in which\n# doubling the quote character escapes it) from the very\n# beginning of $text:\n\n$substring = extractdelimited($text, \"'\", '', \"'\");\n\n# Extract a single- or double- quoted substring from the\n# beginning of $text, optionally after some whitespace\n# (note the list context to protect $text from modification):\n\n($substring) = extractdelimited $text, q{\"'};\n\n# Delete the substring delimited by the first '/' in $text:\n\n$text = join '', (extractdelimited($text,'/','[^/]*')[2,1];\n\nNote that this last example is *not* the same as deleting the first quote-like pattern. For\ninstance, if $text contained the string:\n\n\"if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }\"\n\nthen after the deletion it would contain:\n\n\"if ('.$UNIXCMD/s) { $cmd = $1; }\"\n\nnot:\n\n\"if ('./cmd' =~ ms) { $cmd = $1; }\"\n\nSee \"extractquotelike\" for a (partial) solution to this problem.\n\n\"extractbracketed\"\nLike \"extractdelimited\", the \"extractbracketed\" function takes up to three optional scalar\narguments: a string to extract from, a delimiter specifier, and a prefix pattern. As before,\na missing prefix defaults to optional whitespace and a missing text defaults to $. However,\na missing delimiter specifier defaults to '{}()[]<>' (see below).\n\n\"extractbracketed\" extracts a balanced-bracket-delimited substring (using any one (or more)\nof the user-specified delimiter brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it\nwill also respect quoted unbalanced brackets (see below).\n\nA \"delimiter bracket\" is a bracket in list of delimiters passed as \"extractbracketed\"'s\nsecond argument. Delimiter brackets are specified by giving either the left or right (or\nboth!) versions of the required bracket(s). Note that the order in which two or more\ndelimiter brackets are specified is not significant.\n\nA \"balanced-bracket-delimited substring\" is a substring bounded by matched brackets, such\nthat any other (left or right) delimiter bracket *within* the substring is also matched by\nan opposite (right or left) delimiter bracket *at the same level of nesting*. Any type of\nbracket not in the delimiter list is treated as an ordinary character.\n\nIn other words, each type of bracket specified as a delimiter must be balanced and correctly\nnested within the substring, and any other kind of (\"non-delimiter\") bracket in the\nsubstring is ignored.\n\nFor example, given the string:\n\n$text = \"{ an '[irregularly :-(] {} parenthesized >:-)' string }\";\n\nthen a call to \"extractbracketed\" in a list context:\n\n@result = extractbracketed( $text, '{}' );\n\nwould return:\n\n( \"{ an '[irregularly :-(] {} parenthesized >:-)' string }\" , \"\" , \"\" )\n\nsince both sets of '{..}' brackets are properly nested and evenly balanced. (In a scalar\ncontext just the first element of the array would be returned. In a void context, $text\nwould be replaced by an empty string.)\n\nLikewise the call in:\n\n@result = extractbracketed( $text, '{[' );\n\nwould return the same result, since all sets of both types of specified delimiter brackets\nare correctly nested and balanced.\n\nHowever, the call in:\n\n@result = extractbracketed( $text, '{([<' );\n\nwould fail, returning:\n\n( undef , \"{ an '[irregularly :-(] {} parenthesized >:-)' string }\"  );\n\nbecause the embedded pairs of '(..)'s and '[..]'s are \"cross-nested\" and the embedded '>' is\nunbalanced. (In a scalar context, this call would return an empty string. In a void context,\n$text would be unchanged.)\n\nNote that the embedded single-quotes in the string don't help in this case, since they have\nnot been specified as acceptable delimiters and are therefore treated as non-delimiter\ncharacters (and ignored).\n\nHowever, if a particular species of quote character is included in the delimiter\nspecification, then that type of quote will be correctly handled. for example, if $text is:\n\n$text = '<A HREF=\">>>>\">link</A>';\n\nthen\n\n@result = extractbracketed( $text, '<\">' );\n\nreturns:\n\n( '<A HREF=\">>>>\">', 'link</A>', \"\" )\n\nas expected. Without the specification of \"\"\" as an embedded quoter:\n\n@result = extractbracketed( $text, '<>' );\n\nthe result would be:\n\n( '<A HREF=\">', '>>>\">link</A>', \"\" )\n\nIn addition to the quote delimiters \"'\", \"\"\", and \"`\", full Perl quote-like quoting (i.e.\nq{string}, qq{string}, etc) can be specified by including the letter 'q' as a delimiter.\nHence:\n\n@result = extractbracketed( $text, '<q>' );\n\nwould correctly match something like this:\n\n$text = '<leftop: conj /and/ conj>';\n\nSee also: \"extractquotelike\" and \"extractcodeblock\".\n\n\"extractvariable\"\n\"extractvariable\" extracts any valid Perl variable or variable-involved expression,\nincluding scalars, arrays, hashes, array accesses, hash look-ups, method calls through\nobjects, subroutine calls through subroutine references, etc.\n\nThe subroutine takes up to two optional arguments:\n\n1.  A string to be processed ($ if the string is omitted or \"undef\")\n\n2.  A string specifying a pattern to be matched as a prefix (which is to be skipped). If\nomitted, optional whitespace is skipped.\n\nOn success in a list context, an array of 3 elements is returned. The elements are:\n\n[0] the extracted variable, or variablish expression\n\n[1] the remainder of the input text,\n\n[2] the prefix substring (if any),\n\nOn failure, all of these values (except the remaining text) are \"undef\".\n\nIn a scalar context, \"extractvariable\" returns just the complete substring that matched a\nvariablish expression. \"undef\" is returned on failure. In addition, the original input text\nhas the returned substring (and any prefix) removed from it.\n\nIn a void context, the input text just has the matched substring (and any specified prefix)\nremoved.\n\n\"extracttagged\"\n\"extracttagged\" extracts and segments text between (balanced) specified tags.\n\nThe subroutine takes up to five optional arguments:\n\n1.  A string to be processed ($ if the string is omitted or \"undef\")\n\n2.  A string specifying a pattern to be matched as the opening tag. If the pattern string is\nomitted (or \"undef\") then a pattern that matches any standard XML tag is used.\n\n3.  A string specifying a pattern to be matched at the closing tag. If the pattern string is\nomitted (or \"undef\") then the closing tag is constructed by inserting a \"/\" after any\nleading bracket characters in the actual opening tag that was matched (*not* the pattern\nthat matched the tag). For example, if the opening tag pattern is specified as '{{\\w+}}'\nand actually matched the opening tag \"{{DATA}}\", then the constructed closing tag would\nbe \"{{/DATA}}\".\n\n4.  A string specifying a pattern to be matched as a prefix (which is to be skipped). If\nomitted, optional whitespace is skipped.\n\n5.  A hash reference containing various parsing options (see below)\n\nThe various options that can be specified are:\n\n\"reject => $listref\"\nThe list reference contains one or more strings specifying patterns that must *not*\nappear within the tagged text.\n\nFor example, to extract an HTML link (which should not contain nested links) use:\n\nextracttagged($text, '<A>', '</A>', undef, {reject => ['<A>']} );\n\n\"ignore => $listref\"\nThe list reference contains one or more strings specifying patterns that are *not* to be\ntreated as nested tags within the tagged text (even if they would match the start tag\npattern).\n\nFor example, to extract an arbitrary XML tag, but ignore \"empty\" elements:\n\nextracttagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} );\n\n(also see \"gendelimitedpat\" below).\n\n\"fail => $str\"\nThe \"fail\" option indicates the action to be taken if a matching end tag is not\nencountered (i.e. before the end of the string or some \"reject\" pattern matches). By\ndefault, a failure to match a closing tag causes \"extracttagged\" to immediately fail.\n\nHowever, if the string value associated with <reject> is \"MAX\", then \"extracttagged\"\nreturns the complete text up to the point of failure. If the string is \"PARA\",\n\"extracttagged\" returns only the first paragraph after the tag (up to the first line\nthat is either empty or contains only whitespace characters). If the string is \"\", the\ndefault behaviour (i.e. failure) is reinstated.\n\nFor example, suppose the start tag \"/para\" introduces a paragraph, which then continues\nuntil the next \"/endpara\" tag or until another \"/para\" tag is encountered:\n\n$text = \"/para line 1\\n\\nline 3\\n/para line 4\";\n\nextracttagged($text, '/para', '/endpara', undef,\n{reject => '/para', fail => MAX );\n\n# EXTRACTED: \"/para line 1\\n\\nline 3\\n\"\n\nSuppose instead, that if no matching \"/endpara\" tag is found, the \"/para\" tag refers\nonly to the immediately following paragraph:\n\n$text = \"/para line 1\\n\\nline 3\\n/para line 4\";\n\nextracttagged($text, '/para', '/endpara', undef,\n{reject => '/para', fail => MAX );\n\n# EXTRACTED: \"/para line 1\\n\"\n\nNote that the specified \"fail\" behaviour applies to nested tags as well.\n\nOn success in a list context, an array of 6 elements is returned. The elements are:\n\n[0] the extracted tagged substring (including the outermost tags),\n\n[1] the remainder of the input text,\n\n[2] the prefix substring (if any),\n\n[3] the opening tag\n\n[4] the text between the opening and closing tags\n\n[5] the closing tag (or \"\" if no closing tag was found)\n\nOn failure, all of these values (except the remaining text) are \"undef\".\n\nIn a scalar context, \"extracttagged\" returns just the complete substring that matched a\ntagged text (including the start and end tags). \"undef\" is returned on failure. In addition,\nthe original input text has the returned substring (and any prefix) removed from it.\n\nIn a void context, the input text just has the matched substring (and any specified prefix)\nremoved.\n\n\"genextracttagged\"\n\"genextracttagged\" generates a new anonymous subroutine which extracts text between\n(balanced) specified tags. In other words, it generates a function identical in function to\n\"extracttagged\".\n\nThe difference between \"extracttagged\" and the anonymous subroutines generated by\n\"genextracttagged\", is that those generated subroutines:\n\n*   do not have to reparse tag specification or parsing options every time they are called\n(whereas \"extracttagged\" has to effectively rebuild its tag parser on every call);\n\n*   make use of the new qr// construct to pre-compile the regexes they use (whereas\n\"extracttagged\" uses standard string variable interpolation to create tag-matching\npatterns).\n\nThe subroutine takes up to four optional arguments (the same set as \"extracttagged\" except\nfor the string to be processed). It returns a reference to a subroutine which in turn takes\na single argument (the text to be extracted from).\n\nIn other words, the implementation of \"extracttagged\" is exactly equivalent to:\n\nsub extracttagged\n{\nmy $text = shift;\n$extractor = genextracttagged(@);\nreturn $extractor->($text);\n}\n\n(although \"extracttagged\" is not currently implemented that way).\n\nUsing \"genextracttagged\" to create extraction functions for specific tags is a good idea\nif those functions are going to be called more than once, since their performance is\ntypically twice as good as the more general-purpose \"extracttagged\".\n\n\"extractquotelike\"\n\"extractquotelike\" attempts to recognize, extract, and segment any one of the various Perl\nquotes and quotelike operators (see perlop(3)) Nested backslashed delimiters, embedded\nbalanced bracket delimiters (for the quotelike operators), and trailing modifiers are all\ncaught. For example, in:\n\nextractquotelike 'q # an octothorpe: \\# (not the end of the q!) #'\n\nextractquotelike '  \"You said, \\\"Use sed\\\".\"  '\n\nextractquotelike ' s{([A-Z]{1,8}\\.[A-Z]{3})} /\\L$1\\E/; '\n\nextractquotelike ' tr/\\\\\\/\\\\\\\\/\\\\\\//ds; '\n\nthe full Perl quotelike operations are all extracted correctly.\n\nNote too that, when using the /x modifier on a regex, any comment containing the current\npattern delimiter will cause the regex to be immediately terminated. In other words:\n\n'm /\n(?i)            # CASE INSENSITIVE\n[a-z]          # LEADING ALPHABETIC/UNDERSCORE\n[a-z0-9]*       # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS\n/x'\n\nwill be extracted as if it were:\n\n'm /\n(?i)            # CASE INSENSITIVE\n[a-z]          # LEADING ALPHABETIC/'\n\nThis behaviour is identical to that of the actual compiler.\n\n\"extractquotelike\" takes two arguments: the text to be processed and a prefix to be matched\nat the very beginning of the text. If no prefix is specified, optional whitespace is the\ndefault. If no text is given, $ is used.\n\nIn a list context, an array of 11 elements is returned. The elements are:\n\n[0] the extracted quotelike substring (including trailing modifiers),\n\n[1] the remainder of the input text,\n\n[2] the prefix substring (if any),\n\n[3] the name of the quotelike operator (if any),\n\n[4] the left delimiter of the first block of the operation,\n\n[5] the text of the first block of the operation (that is, the contents of a quote, the\nregex of a match or substitution or the target list of a translation),\n\n[6] the right delimiter of the first block of the operation,\n\n[7] the left delimiter of the second block of the operation (that is, if it is a \"s\", \"tr\",\nor \"y\"),\n\n[8] the text of the second block of the operation (that is, the replacement of a\nsubstitution or the translation list of a translation),\n\n[9] the right delimiter of the second block of the operation (if any),\n\n[10]\nthe trailing modifiers on the operation (if any).\n\nFor each of the fields marked \"(if any)\" the default value on success is an empty string. On\nfailure, all of these values (except the remaining text) are \"undef\".\n\nIn a scalar context, \"extractquotelike\" returns just the complete substring that matched a\nquotelike operation (or \"undef\" on failure). In a scalar or void context, the input text has\nthe same substring (and any specified prefix) removed.\n\nExamples:\n\n# Remove the first quotelike literal that appears in text\n\n$quotelike = extractquotelike($text,'.*?');\n\n# Replace one or more leading whitespace-separated quotelike\n# literals in $ with \"<QLL>\"\n\ndo { $ = join '<QLL>', (extractquotelike)[2,1] } until $@;\n\n\n# Isolate the search pattern in a quotelike operation from $text\n\n($op,$pat) = (extractquotelike $text)[3,5];\nif ($op =~ /[ms]/)\n{\nprint \"search pattern: $pat\\n\";\n}\nelse\n{\nprint \"$op is not a pattern matching operation\\n\";\n}\n\n\"extractquotelike\"\n\"extractquotelike\" can successfully extract \"here documents\" from an input string, but with\nan important caveat in list contexts.\n\nUnlike other types of quote-like literals, a here document is rarely a contiguous substring.\nFor example, a typical piece of code using here document might look like this:\n\n<<'EOMSG' || die;\nThis is the message.\nEOMSG\nexit;\n\nGiven this as an input string in a scalar context, \"extractquotelike\" would correctly\nreturn the string \"<<'EOMSG'\\nThis is the message.\\nEOMSG\", leaving the string \" ||\ndie;\\nexit;\" in the original variable. In other words, the two separate pieces of the here\ndocument are successfully extracted and concatenated.\n\nIn a list context, \"extractquotelike\" would return the list\n\n[0] \"<<'EOMSG'\\nThis is the message.\\nEOMSG\\n\" (i.e. the full extracted here document,\nincluding fore and aft delimiters),\n\n[1] \" || die;\\nexit;\" (i.e. the remainder of the input text, concatenated),\n\n[2] \"\" (i.e. the prefix substring -- trivial in this case),\n\n[3] \"<<\" (i.e. the \"name\" of the quotelike operator)\n\n[4] \"'EOMSG'\" (i.e. the left delimiter of the here document, including any quotes),\n\n[5] \"This is the message.\\n\" (i.e. the text of the here document),\n\n[6] \"EOMSG\" (i.e. the right delimiter of the here document),\n\n[7..10]\n\"\" (a here document has no second left delimiter, second text, second right delimiter,\nor trailing modifiers).\n\nHowever, the matching position of the input variable would be set to \"exit;\" (i.e. *after*\nthe closing delimiter of the here document), which would cause the earlier \" || die;\\nexit;\"\nto be skipped in any sequence of code fragment extractions.\n\nTo avoid this problem, when it encounters a here document whilst extracting from a\nmodifiable string, \"extractquotelike\" silently rearranges the string to an equivalent piece\nof Perl:\n\n<<'EOMSG'\nThis is the message.\nEOMSG\n|| die;\nexit;\n\nin which the here document *is* contiguous. It still leaves the matching position after the\nhere document, but now the rest of the line on which the here document starts is not\nskipped.\n\nTo prevent <extractquotelike> from mucking about with the input in this way (this is the\nonly case where a list-context \"extractquotelike\" does so), you can pass the input variable\nas an interpolated literal:\n\n$quotelike = extractquotelike(\"$var\");\n\n\"extractcodeblock\"\n\"extractcodeblock\" attempts to recognize and extract a balanced bracket delimited substring\nthat may contain unbalanced brackets inside Perl quotes or quotelike operations. That is,\n\"extractcodeblock\" is like a combination of \"extractbracketed\" and \"extractquotelike\".\n\n\"extractcodeblock\" takes the same initial three parameters as \"extractbracketed\": a text\nto process, a set of delimiter brackets to look for, and a prefix to match first. It also\ntakes an optional fourth parameter, which allows the outermost delimiter brackets to be\nspecified separately (see below).\n\nOmitting the first argument (input text) means process $ instead. Omitting the second\nargument (delimiter brackets) indicates that only '{' is to be used. Omitting the third\nargument (prefix argument) implies optional whitespace at the start. Omitting the fourth\nargument (outermost delimiter brackets) indicates that the value of the second argument is\nto be used for the outermost delimiters.\n\nOnce the prefix and the outermost opening delimiter bracket have been recognized, code\nblocks are extracted by stepping through the input text and trying the following\nalternatives in sequence:\n\n1.  Try and match a closing delimiter bracket. If the bracket was the same species as the\nlast opening bracket, return the substring to that point. If the bracket was mismatched,\nreturn an error.\n\n2.  Try to match a quote or quotelike operator. If found, call \"extractquotelike\" to eat\nit. If \"extractquotelike\" fails, return the error it returned. Otherwise go back to\nstep 1.\n\n3.  Try to match an opening delimiter bracket. If found, call \"extractcodeblock\"\nrecursively to eat the embedded block. If the recursive call fails, return an error.\nOtherwise, go back to step 1.\n\n4.  Unconditionally match a bareword or any other single character, and then go back to step\n1.\n\nExamples:\n\n# Find a while loop in the text\n\nif ($text =~ s/.*?while\\s*\\{/{/)\n{\n$loop = \"while \" . extractcodeblock($text);\n}\n\n# Remove the first round-bracketed list (which may include\n# round- or curly-bracketed code blocks or quotelike operators)\n\nextractcodeblock $text, \"(){}\", '[^(]*';\n\nThe ability to specify a different outermost delimiter bracket is useful in some\ncircumstances. For example, in the Parse::RecDescent module, parser actions which are to be\nperformed only on a successful parse are specified using a \"<defer:...>\" directive. For\nexample:\n\nsentence: subject verb object\n<defer: {$::theVerb = $item{verb}} >\n\nParse::RecDescent uses \"extractcodeblock($text, '{}<>')\" to extract the code within the\n\"<defer:...>\" directive, but there's a problem.\n\nA deferred action like this:\n\n<defer: {if ($count>10) {$count--}} >\n\nwill be incorrectly parsed as:\n\n<defer: {if ($count>\n\nbecause the \"less than\" operator is interpreted as a closing delimiter.\n\nBut, by extracting the directive using \"extractcodeblock($text, '{}', undef, '<>')\" the '>'\ncharacter is only treated as a delimited at the outermost level of the code block, so the\ndirective is parsed correctly.\n\n\"extractmultiple\"\nThe \"extractmultiple\" subroutine takes a string to be processed and a list of extractors\n(subroutines or regular expressions) to apply to that string.\n\nIn an array context \"extractmultiple\" returns an array of substrings of the original\nstring, as extracted by the specified extractors. In a scalar context, \"extractmultiple\"\nreturns the first substring successfully extracted from the original string. In both scalar\nand void contexts the original string has the first successfully extracted substring removed\nfrom it. In all contexts \"extractmultiple\" starts at the current \"pos\" of the string, and\nsets that \"pos\" appropriately after it matches.\n\nHence, the aim of a call to \"extractmultiple\" in a list context is to split the processed\nstring into as many non-overlapping fields as possible, by repeatedly applying each of the\nspecified extractors to the remainder of the string. Thus \"extractmultiple\" is a\ngeneralized form of Perl's \"split\" subroutine.\n\nThe subroutine takes up to four optional arguments:\n\n1.  A string to be processed ($ if the string is omitted or \"undef\")\n\n2.  A reference to a list of subroutine references and/or qr// objects and/or literal\nstrings and/or hash references, specifying the extractors to be used to split the\nstring. If this argument is omitted (or \"undef\") the list:\n\n[\nsub { extractvariable($[0], '') },\nsub { extractquotelike($[0],'') },\nsub { extractcodeblock($[0],'{}','') },\n]\n\nis used.\n\n3.  An number specifying the maximum number of fields to return. If this argument is omitted\n(or \"undef\"), split continues as long as possible.\n\nIf the third argument is *N*, then extraction continues until *N* fields have been\nsuccessfully extracted, or until the string has been completely processed.\n\nNote that in scalar and void contexts the value of this argument is automatically reset\nto 1 (under \"-w\", a warning is issued if the argument has to be reset).\n\n4.  A value indicating whether unmatched substrings (see below) within the text should be\nskipped or returned as fields. If the value is true, such substrings are skipped.\nOtherwise, they are returned.\n\nThe extraction process works by applying each extractor in sequence to the text string.\n\nIf the extractor is a subroutine it is called in a list context and is expected to return a\nlist of a single element, namely the extracted text. It may optionally also return two\nfurther arguments: a string representing the text left after extraction (like $' for a\npattern match), and a string representing any prefix skipped before the extraction (like $`\nin a pattern match). Note that this is designed to facilitate the use of other\nText::Balanced subroutines with \"extractmultiple\". Note too that the value returned by an\nextractor subroutine need not bear any relationship to the corresponding substring of the\noriginal text (see examples below).\n\nIf the extractor is a precompiled regular expression or a string, it is matched against the\ntext in a scalar context with a leading '\\G' and the gc modifiers enabled. The extracted\nvalue is either $1 if that variable is defined after the match, or else the complete match\n(i.e. $&).\n\nIf the extractor is a hash reference, it must contain exactly one element. The value of that\nelement is one of the above extractor types (subroutine reference, regular expression, or\nstring). The key of that element is the name of a class into which the successful return\nvalue of the extractor will be blessed.\n\nIf an extractor returns a defined value, that value is immediately treated as the next\nextracted field and pushed onto the list of fields. If the extractor was specified in a hash\nreference, the field is also blessed into the appropriate class,\n\nIf the extractor fails to match (in the case of a regex extractor), or returns an empty list\nor an undefined value (in the case of a subroutine extractor), it is assumed to have failed\nto extract. If none of the extractor subroutines succeeds, then one character is extracted\nfrom the start of the text and the extraction subroutines reapplied. Characters which are\nthus removed are accumulated and eventually become the next field (unless the fourth\nargument is true, in which case they are discarded).\n\nFor example, the following extracts substrings that are valid Perl variables:\n\n@fields = extractmultiple($text,\n[ sub { extractvariable($[0]) } ],\nundef, 1);\n\nThis example separates a text into fields which are quote delimited, curly bracketed, and\nanything else. The delimited and bracketed parts are also blessed to identify them (the\n\"anything else\" is unblessed):\n\n@fields = extractmultiple($text,\n[\n{ Delim => sub { extractdelimited($[0],q{'\"}) } },\n{ Brack => sub { extractbracketed($[0],'{}') } },\n]);\n\nThis call extracts the next single substring that is a valid Perl quotelike operator (and\nremoves it from $text):\n\n$quotelike = extractmultiple($text,\n[\nsub { extractquotelike($[0]) },\n], undef, 1);\n\nFinally, here is yet another way to do comma-separated value parsing:\n\n@fields = extractmultiple($csvtext,\n[\nsub { extractdelimited($[0],q{'\"}) },\nqr/([^,]+)(.*)/,\n],\nundef,1);\n\nThe list in the second argument means: *\"Try and extract a ' or \" delimited string,\notherwise extract anything up to a comma...\"*. The undef third argument means: *\"...as many\ntimes as possible...\"*, and the true value in the fourth argument means *\"...discarding\nanything else that appears (i.e. the commas)\"*.\n\nIf you wanted the commas preserved as separate fields (i.e. like split does if your split\npattern has capturing parentheses), you would just make the last parameter undefined (or\nremove it).\n\n\"gendelimitedpat\"\nThe \"gendelimitedpat\" subroutine takes a single (string) argument and > builds a\nFriedl-style optimized regex that matches a string delimited by any one of the characters in\nthe single argument. For example:\n\ngendelimitedpat(q{'\"})\n\nreturns the regex:\n\n(?:\\\"(?:\\\\\\\"|(?!\\\").)*\\\"|\\'(?:\\\\\\'|(?!\\').)*\\')\n\nNote that the specified delimiters are automatically quotemeta'd.\n\nA typical use of \"gendelimitedpat\" would be to build special purpose tags for\n\"extracttagged\". For example, to properly ignore \"empty\" XML elements (which might contain\nquoted strings):\n\nmy $emptytag = '<(' . gendelimitedpat(q{'\"}) . '|.)+/>';\n\nextracttagged($text, undef, undef, undef, {ignore => [$emptytag]} );\n\n\"gendelimitedpat\" may also be called with an optional second argument, which specifies the\n\"escape\" character(s) to be used for each delimiter. For example to match a Pascal-style\nstring (where ' is the delimiter and '' is a literal ' within the string):\n\ngendelimitedpat(q{'},q{'});\n\nDifferent escape characters can be specified for different delimiters. For example, to\nspecify that '/' is the escape for single quotes and '%' is the escape for double quotes:\n\ngendelimitedpat(q{'\"},q{/%});\n\nIf more delimiters than escape chars are specified, the last escape char is used for the\nremaining delimiters. If no escape char is specified for a given specified delimiter, '\\' is\nused.\n\n\"delimitedpat\"\nNote that \"gendelimitedpat\" was previously called \"delimitedpat\". That name may still be\nused, but is now deprecated.\n\n### DIAGNOSTICS\n\nIn a list context, all the functions return \"(undef,$originaltext)\" on failure. In a scalar\ncontext, failure is indicated by returning \"undef\" (in this case the input text is not modified\nin any way).\n\nIn addition, on failure in *any* context, the $@ variable is set. Accessing \"$@->{error}\"\nreturns one of the error diagnostics listed below. Accessing \"$@->{pos}\" returns the offset into\nthe original string at which the error was detected (although not necessarily where it\noccurred!) Printing $@ directly produces the error message, with the offset appended. On\nsuccess, the $@ variable is guaranteed to be \"undef\".\n\nThe available diagnostics are:\n\n\"Did not find a suitable bracket: \"%s\"\"\nThe delimiter provided to \"extractbracketed\" was not one of '()[]<>{}'.\n\n\"Did not find prefix: /%s/\"\nA non-optional prefix was specified but wasn't found at the start of the text.\n\n\"Did not find opening bracket after prefix: \"%s\"\"\n\"extractbracketed\" or \"extractcodeblock\" was expecting a particular kind of bracket at the\nstart of the text, and didn't find it.\n\n\"No quotelike operator found after prefix: \"%s\"\"\n\"extractquotelike\" didn't find one of the quotelike operators \"q\", \"qq\", \"qw\", \"qx\", \"s\",\n\"tr\" or \"y\" at the start of the substring it was extracting.\n\n\"Unmatched closing bracket: \"%c\"\"\n\"extractbracketed\", \"extractquotelike\" or \"extractcodeblock\" encountered a closing\nbracket where none was expected.\n\n\"Unmatched opening bracket(s): \"%s\"\"\n\"extractbracketed\", \"extractquotelike\" or \"extractcodeblock\" ran out of characters in the\ntext before closing one or more levels of nested brackets.\n\n\"Unmatched embedded quote (%s)\"\n\"extractbracketed\" attempted to match an embedded quoted substring, but failed to find a\nclosing quote to match it.\n\n\"Did not find closing delimiter to match '%s'\"\n\"extractquotelike\" was unable to find a closing delimiter to match the one that opened the\nquote-like operation.\n\n\"Mismatched closing bracket: expected \"%c\" but found \"%s\"\"\n\"extractbracketed\", \"extractquotelike\" or \"extractcodeblock\" found a valid bracket\ndelimiter, but it was the wrong species. This usually indicates a nesting error, but may\nindicate incorrect quoting or escaping.\n\n\"No block delimiter found after quotelike \"%s\"\"\n\"extractquotelike\" or \"extractcodeblock\" found one of the quotelike operators \"q\", \"qq\",\n\"qw\", \"qx\", \"s\", \"tr\" or \"y\" without a suitable block after it.\n\n\"Did not find leading dereferencer\"\n\"extractvariable\" was expecting one of '$', '@', or '%' at the start of a variable, but\ndidn't find any of them.\n\n\"Bad identifier after dereferencer\"\n\"extractvariable\" found a '$', '@', or '%' indicating a variable, but that character was\nnot followed by a legal Perl identifier.\n\n\"Did not find expected opening bracket at %s\"\n\"extractcodeblock\" failed to find any of the outermost opening brackets that were\nspecified.\n\n\"Improperly nested codeblock at %s\"\nA nested code block was found that started with a delimiter that was specified as being only\nto be used as an outermost bracket.\n\n\"Missing second block for quotelike \"%s\"\"\n\"extractcodeblock\" or \"extractquotelike\" found one of the quotelike operators \"s\", \"tr\" or\n\"y\" followed by only one block.\n\n\"No match found for opening bracket\"\n\"extractcodeblock\" failed to find a closing bracket to match the outermost opening bracket.\n\n\"Did not find opening tag: /%s/\"\n\"extracttagged\" did not find a suitable opening tag (after any specified prefix was\nremoved).\n\n\"Unable to construct closing tag to match: /%s/\"\n\"extracttagged\" matched the specified opening tag and tried to modify the matched text to\nproduce a matching closing tag (because none was specified). It failed to generate the\nclosing tag, almost certainly because the opening tag did not start with a bracket of some\nkind.\n\n\"Found invalid nested tag: %s\"\n\"extracttagged\" found a nested tag that appeared in the \"reject\" list (and the failure mode\nwas not \"MAX\" or \"PARA\").\n\n\"Found unbalanced nested tag: %s\"\n\"extracttagged\" found a nested opening tag that was not matched by a corresponding nested\nclosing tag (and the failure mode was not \"MAX\" or \"PARA\").\n\n\"Did not find closing tag\"\n\"extracttagged\" reached the end of the text without finding a closing tag to match the\noriginal opening tag (and the failure mode was not \"MAX\" or \"PARA\").\n\n### EXPORTS\n\nThe following symbols are, or can be, exported by this module:\n\nDefault Exports\n*None*.\n\nOptional Exports\n\"extractdelimited\", \"extractbracketed\", \"extractquotelike\", \"extractcodeblock\",\n\"extractvariable\", \"extracttagged\", \"extractmultiple\", \"gendelimitedpat\",\n\"genextracttagged\", \"delimitedpat\".\n\nExport Tags\n\n\":ALL\"\n\"extractdelimited\", \"extractbracketed\", \"extractquotelike\", \"extractcodeblock\",\n\"extractvariable\", \"extracttagged\", \"extractmultiple\", \"gendelimitedpat\",\n\"genextracttagged\", \"delimitedpat\".\n\n### KNOWN BUGS\n\nSee <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Text-Balanced>.\n\n### FEEDBACK\n\nPatches, bug reports, suggestions or any other feedback is welcome.\n\nPatches can be sent as GitHub pull requests at\n<https://github.com/steve-m-hay/Text-Balanced/pulls>.\n\nBug reports and suggestions can be made on the CPAN Request Tracker at\n<https://rt.cpan.org/Public/Bug/Report.html?Queue=Text-Balanced>.\n\nCurrently active requests on the CPAN Request Tracker can be viewed at\n<https://rt.cpan.org/Public/Dist/Display.html?Status=Active;Queue=Text-Balanced>.\n\nPlease test this distribution. See CPAN Testers Reports at <https://www.cpantesters.org/> for\ndetails of how to get involved.\n\nPrevious test results on CPAN Testers Reports can be viewed at\n<https://www.cpantesters.org/distro/T/Text-Balanced.html>.\n\nPlease rate this distribution on CPAN Ratings at\n<https://cpanratings.perl.org/rate/?distribution=Text-Balanced>.\n\n### AVAILABILITY\n\nThe latest version of this module is available from CPAN (see \"CPAN\" in perlmodlib for details)\nat\n\n<https://metacpan.org/release/Text-Balanced> or\n\n<https://www.cpan.org/authors/id/S/SH/SHAY/> or\n\n<https://www.cpan.org/modules/by-module/Text/>.\n\nThe latest source code is available from GitHub at\n<https://github.com/steve-m-hay/Text-Balanced>.\n\n### INSTALLATION\n\nSee the INSTALL file.\n\n### AUTHOR\n\nDamian Conway <damian@conway.org <mailto:damian@conway.org>>.\n\nSteve Hay <shay@cpan.org <mailto:shay@cpan.org>> is now maintaining Text::Balanced as of version\n2.03.\n\n### COPYRIGHT\n\nCopyright (C) 1997-2001 Damian Conway. All rights reserved.\n\nCopyright (C) 2009 Adam Kennedy.\n\nCopyright (C) 2015, 2020 Steve Hay. All rights reserved.\n\n### LICENCE\n\nThis module is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself, i.e. under the terms of either the GNU General Public License or the Artistic\nLicense, as specified in the LICENCE file.\n\n### VERSION\n\nVersion 2.04\n\n### DATE\n\n11 Dec 2020\n\n### HISTORY\n\nSee the Changes file.\n\n"
        }
    ],
    "structuredContent": {
        "command": "Text::Balanced",
        "section": "",
        "mode": "perldoc",
        "summary": "Text::Balanced - Extract delimited text sequences from strings.",
        "synopsis": "use Text::Balanced qw (\nextractdelimited\nextractbracketed\nextractquotelike\nextractcodeblock\nextractvariable\nextracttagged\nextractmultiple\ngendelimitedpat\ngenextracttagged\n);\n# Extract the initial substring of $text that is delimited by\n# two (unescaped) instances of the first character in $delim.\n($extracted, $remainder) = extractdelimited($text,$delim);\n# Extract the initial substring of $text that is bracketed\n# with a delimiter(s) specified by $delim (where the string\n# in $delim contains one or more of '(){}[]<>').\n($extracted, $remainder) = extractbracketed($text,$delim);\n# Extract the initial substring of $text that is bounded by\n# an XML tag.\n($extracted, $remainder) = extracttagged($text);\n# Extract the initial substring of $text that is bounded by\n# a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags\n($extracted, $remainder) =\nextracttagged($text,\"BEGIN\",\"END\",undef,{bad=>[\"BEGIN\"]});\n# Extract the initial substring of $text that represents a\n# Perl \"quote or quote-like operation\"\n($extracted, $remainder) = extractquotelike($text);\n# Extract the initial substring of $text that represents a block\n# of Perl code, bracketed by any of character(s) specified by $delim\n# (where the string $delim contains one or more of '(){}[]<>').\n($extracted, $remainder) = extractcodeblock($text,$delim);\n# Extract the initial substrings of $text that would be extracted by\n# one or more sequential applications of the specified functions\n# or regular expressions\n@extracted = extractmultiple($text,\n[ \\&extractbracketed,\n\\&extractquotelike,\n\\&someotherextractorsub,\nqr/[xyz]*/,\n'literal',\n]);\n# Create a string representing an optimized pattern (a la Friedl)\n# that matches a substring delimited by any of the specified characters\n# (in this case: any type of quote or a slash)\n$patstring = gendelimitedpat(q{'\"`/});\n# Generate a reference to an anonymous sub that is just like extracttagged\n# but pre-compiled and optimized for a specific pair of tags, and\n# consequently much faster (i.e. 3 times faster). It uses qr// for better\n# performance on repeated calls.\n$extracthead = genextracttagged('<HEAD>','</HEAD>');\n($extracted, $remainder) = $extracthead->($text);",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 71,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 10,
                "subsections": [
                    {
                        "name": "General Behaviour in List Contexts",
                        "lines": 24
                    },
                    {
                        "name": "General Behaviour in Scalar and Void Contexts",
                        "lines": 24
                    },
                    {
                        "name": "Functions",
                        "lines": 721
                    }
                ]
            },
            {
                "name": "DIAGNOSTICS",
                "lines": 96,
                "subsections": []
            },
            {
                "name": "EXPORTS",
                "lines": 17,
                "subsections": []
            },
            {
                "name": "KNOWN BUGS",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "FEEDBACK",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "AVAILABILITY",
                "lines": 12,
                "subsections": []
            },
            {
                "name": "INSTALLATION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 5,
                "subsections": []
            },
            {
                "name": "COPYRIGHT",
                "lines": 6,
                "subsections": []
            },
            {
                "name": "LICENCE",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DATE",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "HISTORY",
                "lines": 2,
                "subsections": []
            }
        ]
    }
}