1Text::Balanced(3pm) Perl Programmers Reference Guide Text::Balanced(3pm)
2
3
4
6 Text::Balanced - Extract delimited text sequences from strings.
7
9 use Text::Balanced qw (
10 extract_delimited
11 extract_bracketed
12 extract_quotelike
13 extract_codeblock
14 extract_variable
15 extract_tagged
16 extract_multiple
17
18 gen_delimited_pat
19 gen_extract_tagged
20 );
21
22 # Extract the initial substring of $text that is delimited by
23 # two (unescaped) instances of the first character in $delim.
24
25 ($extracted, $remainder) = extract_delimited($text,$delim);
26
27
28 # Extract the initial substring of $text that is bracketed
29 # with a delimiter(s) specified by $delim (where the string
30 # in $delim contains one or more of '(){}[]<>').
31
32 ($extracted, $remainder) = extract_bracketed($text,$delim);
33
34
35 # Extract the initial substring of $text that is bounded by
36 # an XML tag.
37
38 ($extracted, $remainder) = extract_tagged($text);
39
40
41 # Extract the initial substring of $text that is bounded by
42 # a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags
43
44 ($extracted, $remainder) =
45 extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]});
46
47
48 # Extract the initial substring of $text that represents a
49 # Perl "quote or quote-like operation"
50
51 ($extracted, $remainder) = extract_quotelike($text);
52
53
54 # Extract the initial substring of $text that represents a block
55 # of Perl code, bracketed by any of character(s) specified by $delim
56 # (where the string $delim contains one or more of '(){}[]<>').
57
58 ($extracted, $remainder) = extract_codeblock($text,$delim);
59
60
61 # Extract the initial substrings of $text that would be extracted by
62 # one or more sequential applications of the specified functions
63 # or regular expressions
64
65 @extracted = extract_multiple($text,
66 [ \&extract_bracketed,
67 \&extract_quotelike,
68 \&some_other_extractor_sub,
69 qr/[xyz]*/,
70 'literal',
71 ]);
72
73 # Create a string representing an optimized pattern (a la Friedl) #
74 that matches a substring delimited by any of the specified characters #
75 (in this case: any type of quote or a slash)
76
77 $patstring = gen_delimited_pat(q{'"`/});
78
79 # Generate a reference to an anonymous sub that is just like
80 extract_tagged # but pre-compiled and optimized for a specific pair of
81 tags, and consequently # much faster (i.e. 3 times faster). It uses
82 qr// for better performance on # repeated calls, so it only works under
83 Perl 5.005 or later.
84
85 $extract_head = gen_extract_tagged('<HEAD>','</HEAD>');
86
87 ($extracted, $remainder) = $extract_head->($text);
88
90 The various "extract_..." subroutines may be used to extract a
91 delimited substring, possibly after skipping a specified prefix string.
92 By default, that prefix is optional whitespace ("/\s*/"), but you can
93 change it to whatever you wish (see below).
94
95 The substring to be extracted must appear at the current "pos" location
96 of the string's variable (or at index zero, if no "pos" position is
97 defined). In other words, the "extract_..." subroutines don't extract
98 the first occurrence of a substring anywhere in a string (like an
99 unanchored regex would). Rather, they extract an occurrence of the
100 substring appearing immediately at the current matching position in the
101 string (like a "\G"-anchored regex would).
102
103 General behaviour in list contexts
104 In a list context, all the subroutines return a list, the first three
105 elements of which are always:
106
107 [0] The extracted string, including the specified delimiters. If the
108 extraction fails "undef" is returned.
109
110 [1] The remainder of the input string (i.e. the characters after the
111 extracted string). On failure, the entire string is returned.
112
113 [2] The skipped prefix (i.e. the characters before the extracted
114 string). On failure, "undef" is returned.
115
116 Note that in a list context, the contents of the original input text
117 (the first argument) are not modified in any way.
118
119 However, if the input text was passed in a variable, that variable's
120 "pos" value is updated to point at the first character after the
121 extracted text. That means that in a list context the various
122 subroutines can be used much like regular expressions. For example:
123
124 while ( $next = (extract_quotelike($text))[0] )
125 {
126 # process next quote-like (in $next)
127 }
128
129 General behaviour in scalar and void contexts
130 In a scalar context, the extracted string is returned, having first
131 been removed from the input text. Thus, the following code also
132 processes each quote-like operation, but actually removes them from
133 $text:
134
135 while ( $next = extract_quotelike($text) )
136 {
137 # process next quote-like (in $next)
138 }
139
140 Note that if the input text is a read-only string (i.e. a literal), no
141 attempt is made to remove the extracted text.
142
143 In a void context the behaviour of the extraction subroutines is
144 exactly the same as in a scalar context, except (of course) that the
145 extracted substring is not returned.
146
147 A note about prefixes
148 Prefix patterns are matched without any trailing modifiers ("/gimsox"
149 etc.) This can bite you if you're expecting a prefix specification
150 like '.*?(?=<H1>)' to skip everything up to the first <H1> tag. Such a
151 prefix pattern will only succeed if the <H1> tag is on the current
152 line, since . normally doesn't match newlines.
153
154 To overcome this limitation, you need to turn on /s matching within the
155 prefix pattern, using the "(?s)" directive: '(?s).*?(?=<H1>)'
156
157 "extract_delimited"
158 The "extract_delimited" function formalizes the common idiom of
159 extracting a single-character-delimited substring from the start of a
160 string. For example, to extract a single-quote delimited string, the
161 following code is typically used:
162
163 ($remainder = $text) =~ s/\A('(\\.|[^'])*')//s;
164 $extracted = $1;
165
166 but with "extract_delimited" it can be simplified to:
167
168 ($extracted,$remainder) = extract_delimited($text, "'");
169
170 "extract_delimited" takes up to four scalars (the input text, the
171 delimiters, a prefix pattern to be skipped, and any escape characters)
172 and extracts the initial substring of the text that is appropriately
173 delimited. If the delimiter string has multiple characters, the first
174 one encountered in the text is taken to delimit the substring. The
175 third argument specifies a prefix pattern that is to be skipped (but
176 must be present!) before the substring is extracted. The final
177 argument specifies the escape character to be used for each delimiter.
178
179 All arguments are optional. If the escape characters are not specified,
180 every delimiter is escaped with a backslash ("\"). If the prefix is
181 not specified, the pattern '\s*' - optional whitespace - is used. If
182 the delimiter set is also not specified, the set "/["'`]/" is used. If
183 the text to be processed is not specified either, $_ is used.
184
185 In list context, "extract_delimited" returns a array of three elements,
186 the extracted substring (including the surrounding delimiters), the
187 remainder of the text, and the skipped prefix (if any). If a suitable
188 delimited substring is not found, the first element of the array is the
189 empty string, the second is the complete original text, and the prefix
190 returned in the third element is an empty string.
191
192 In a scalar context, just the extracted substring is returned. In a
193 void context, the extracted substring (and any prefix) are simply
194 removed from the beginning of the first argument.
195
196 Examples:
197
198 # Remove a single-quoted substring from the very beginning of $text:
199
200 $substring = extract_delimited($text, "'", '');
201
202 # Remove a single-quoted Pascalish substring (i.e. one in which
203 # doubling the quote character escapes it) from the very
204 # beginning of $text:
205
206 $substring = extract_delimited($text, "'", '', "'");
207
208 # Extract a single- or double- quoted substring from the
209 # beginning of $text, optionally after some whitespace
210 # (note the list context to protect $text from modification):
211
212 ($substring) = extract_delimited $text, q{"'};
213
214
215 # Delete the substring delimited by the first '/' in $text:
216
217 $text = join '', (extract_delimited($text,'/','[^/]*')[2,1];
218
219 Note that this last example is not the same as deleting the first
220 quote-like pattern. For instance, if $text contained the string:
221
222 "if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }"
223
224 then after the deletion it would contain:
225
226 "if ('.$UNIXCMD/s) { $cmd = $1; }"
227
228 not:
229
230 "if ('./cmd' =~ ms) { $cmd = $1; }"
231
232 See "extract_quotelike" for a (partial) solution to this problem.
233
234 "extract_bracketed"
235 Like "extract_delimited", the "extract_bracketed" function takes up to
236 three optional scalar arguments: a string to extract from, a delimiter
237 specifier, and a prefix pattern. As before, a missing prefix defaults
238 to optional whitespace and a missing text defaults to $_. However, a
239 missing delimiter specifier defaults to '{}()[]<>' (see below).
240
241 "extract_bracketed" extracts a balanced-bracket-delimited substring
242 (using any one (or more) of the user-specified delimiter brackets:
243 '(..)', '{..}', '[..]', or '<..>'). Optionally it will also respect
244 quoted unbalanced brackets (see below).
245
246 A "delimiter bracket" is a bracket in list of delimiters passed as
247 "extract_bracketed"'s second argument. Delimiter brackets are specified
248 by giving either the left or right (or both!) versions of the required
249 bracket(s). Note that the order in which two or more delimiter brackets
250 are specified is not significant.
251
252 A "balanced-bracket-delimited substring" is a substring bounded by
253 matched brackets, such that any other (left or right) delimiter bracket
254 within the substring is also matched by an opposite (right or left)
255 delimiter bracket at the same level of nesting. Any type of bracket not
256 in the delimiter list is treated as an ordinary character.
257
258 In other words, each type of bracket specified as a delimiter must be
259 balanced and correctly nested within the substring, and any other kind
260 of ("non-delimiter") bracket in the substring is ignored.
261
262 For example, given the string:
263
264 $text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }";
265
266 then a call to "extract_bracketed" in a list context:
267
268 @result = extract_bracketed( $text, '{}' );
269
270 would return:
271
272 ( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" )
273
274 since both sets of '{..}' brackets are properly nested and evenly
275 balanced. (In a scalar context just the first element of the array
276 would be returned. In a void context, $text would be replaced by an
277 empty string.)
278
279 Likewise the call in:
280
281 @result = extract_bracketed( $text, '{[' );
282
283 would return the same result, since all sets of both types of specified
284 delimiter brackets are correctly nested and balanced.
285
286 However, the call in:
287
288 @result = extract_bracketed( $text, '{([<' );
289
290 would fail, returning:
291
292 ( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }" );
293
294 because the embedded pairs of '(..)'s and '[..]'s are "cross-nested"
295 and the embedded '>' is unbalanced. (In a scalar context, this call
296 would return an empty string. In a void context, $text would be
297 unchanged.)
298
299 Note that the embedded single-quotes in the string don't help in this
300 case, since they have not been specified as acceptable delimiters and
301 are therefore treated as non-delimiter characters (and ignored).
302
303 However, if a particular species of quote character is included in the
304 delimiter specification, then that type of quote will be correctly
305 handled. for example, if $text is:
306
307 $text = '<A HREF=">>>>">link</A>';
308
309 then
310
311 @result = extract_bracketed( $text, '<">' );
312
313 returns:
314
315 ( '<A HREF=">>>>">', 'link</A>', "" )
316
317 as expected. Without the specification of """ as an embedded quoter:
318
319 @result = extract_bracketed( $text, '<>' );
320
321 the result would be:
322
323 ( '<A HREF=">', '>>>">link</A>', "" )
324
325 In addition to the quote delimiters "'", """, and "`", full Perl quote-
326 like quoting (i.e. q{string}, qq{string}, etc) can be specified by
327 including the letter 'q' as a delimiter. Hence:
328
329 @result = extract_bracketed( $text, '<q>' );
330
331 would correctly match something like this:
332
333 $text = '<leftop: conj /and/ conj>';
334
335 See also: "extract_quotelike" and "extract_codeblock".
336
337 "extract_variable"
338 "extract_variable" extracts any valid Perl variable or variable-
339 involved expression, including scalars, arrays, hashes, array accesses,
340 hash look-ups, method calls through objects, subroutine calls through
341 subroutine references, etc.
342
343 The subroutine takes up to two optional arguments:
344
345 1. A string to be processed ($_ if the string is omitted or "undef")
346
347 2. A string specifying a pattern to be matched as a prefix (which is
348 to be skipped). If omitted, optional whitespace is skipped.
349
350 On success in a list context, an array of 3 elements is returned. The
351 elements are:
352
353 [0] the extracted variable, or variablish expression
354
355 [1] the remainder of the input text,
356
357 [2] the prefix substring (if any),
358
359 On failure, all of these values (except the remaining text) are
360 "undef".
361
362 In a scalar context, "extract_variable" returns just the complete
363 substring that matched a variablish expression. "undef" is returned on
364 failure. In addition, the original input text has the returned
365 substring (and any prefix) removed from it.
366
367 In a void context, the input text just has the matched substring (and
368 any specified prefix) removed.
369
370 "extract_tagged"
371 "extract_tagged" extracts and segments text between (balanced)
372 specified tags.
373
374 The subroutine takes up to five optional arguments:
375
376 1. A string to be processed ($_ if the string is omitted or "undef")
377
378 2. A string specifying a pattern to be matched as the opening tag. If
379 the pattern string is omitted (or "undef") then a pattern that
380 matches any standard XML tag is used.
381
382 3. A string specifying a pattern to be matched at the closing tag. If
383 the pattern string is omitted (or "undef") then the closing tag is
384 constructed by inserting a "/" after any leading bracket characters
385 in the actual opening tag that was matched (not the pattern that
386 matched the tag). For example, if the opening tag pattern is
387 specified as '{{\w+}}' and actually matched the opening tag
388 "{{DATA}}", then the constructed closing tag would be "{{/DATA}}".
389
390 4. A string specifying a pattern to be matched as a prefix (which is
391 to be skipped). If omitted, optional whitespace is skipped.
392
393 5. A hash reference containing various parsing options (see below)
394
395 The various options that can be specified are:
396
397 "reject => $listref"
398 The list reference contains one or more strings specifying patterns
399 that must not appear within the tagged text.
400
401 For example, to extract an HTML link (which should not contain
402 nested links) use:
403
404 extract_tagged($text, '<A>', '</A>', undef, {reject => ['<A>']} );
405
406 "ignore => $listref"
407 The list reference contains one or more strings specifying patterns
408 that are not be be treated as nested tags within the tagged text
409 (even if they would match the start tag pattern).
410
411 For example, to extract an arbitrary XML tag, but ignore "empty"
412 elements:
413
414 extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} );
415
416 (also see "gen_delimited_pat" below).
417
418 "fail => $str"
419 The "fail" option indicates the action to be taken if a matching
420 end tag is not encountered (i.e. before the end of the string or
421 some "reject" pattern matches). By default, a failure to match a
422 closing tag causes "extract_tagged" to immediately fail.
423
424 However, if the string value associated with <reject> is "MAX",
425 then "extract_tagged" returns the complete text up to the point of
426 failure. If the string is "PARA", "extract_tagged" returns only
427 the first paragraph after the tag (up to the first line that is
428 either empty or contains only whitespace characters). If the
429 string is "", the the default behaviour (i.e. failure) is
430 reinstated.
431
432 For example, suppose the start tag "/para" introduces a paragraph,
433 which then continues until the next "/endpara" tag or until another
434 "/para" tag is encountered:
435
436 $text = "/para line 1\n\nline 3\n/para line 4";
437
438 extract_tagged($text, '/para', '/endpara', undef,
439 {reject => '/para', fail => MAX );
440
441 # EXTRACTED: "/para line 1\n\nline 3\n"
442
443 Suppose instead, that if no matching "/endpara" tag is found, the
444 "/para" tag refers only to the immediately following paragraph:
445
446 $text = "/para line 1\n\nline 3\n/para line 4";
447
448 extract_tagged($text, '/para', '/endpara', undef,
449 {reject => '/para', fail => MAX );
450
451 # EXTRACTED: "/para line 1\n"
452
453 Note that the specified "fail" behaviour applies to nested tags as
454 well.
455
456 On success in a list context, an array of 6 elements is returned. The
457 elements are:
458
459 [0] the extracted tagged substring (including the outermost tags),
460
461 [1] the remainder of the input text,
462
463 [2] the prefix substring (if any),
464
465 [3] the opening tag
466
467 [4] the text between the opening and closing tags
468
469 [5] the closing tag (or "" if no closing tag was found)
470
471 On failure, all of these values (except the remaining text) are
472 "undef".
473
474 In a scalar context, "extract_tagged" returns just the complete
475 substring that matched a tagged text (including the start and end
476 tags). "undef" is returned on failure. In addition, the original input
477 text has the returned substring (and any prefix) removed from it.
478
479 In a void context, the input text just has the matched substring (and
480 any specified prefix) removed.
481
482 "gen_extract_tagged"
483 (Note: This subroutine is only available under Perl5.005)
484
485 "gen_extract_tagged" generates a new anonymous subroutine which
486 extracts text between (balanced) specified tags. In other words, it
487 generates a function identical in function to "extract_tagged".
488
489 The difference between "extract_tagged" and the anonymous subroutines
490 generated by "gen_extract_tagged", is that those generated subroutines:
491
492 · do not have to reparse tag specification or parsing options every
493 time they are called (whereas "extract_tagged" has to effectively
494 rebuild its tag parser on every call);
495
496 · make use of the new qr// construct to pre-compile the regexes they
497 use (whereas "extract_tagged" uses standard string variable
498 interpolation to create tag-matching patterns).
499
500 The subroutine takes up to four optional arguments (the same set as
501 "extract_tagged" except for the string to be processed). It returns a
502 reference to a subroutine which in turn takes a single argument (the
503 text to be extracted from).
504
505 In other words, the implementation of "extract_tagged" is exactly
506 equivalent to:
507
508 sub extract_tagged
509 {
510 my $text = shift;
511 $extractor = gen_extract_tagged(@_);
512 return $extractor->($text);
513 }
514
515 (although "extract_tagged" is not currently implemented that way, in
516 order to preserve pre-5.005 compatibility).
517
518 Using "gen_extract_tagged" to create extraction functions for specific
519 tags is a good idea if those functions are going to be called more than
520 once, since their performance is typically twice as good as the more
521 general-purpose "extract_tagged".
522
523 "extract_quotelike"
524 "extract_quotelike" attempts to recognize, extract, and segment any one
525 of the various Perl quotes and quotelike operators (see perlop(3))
526 Nested backslashed delimiters, embedded balanced bracket delimiters
527 (for the quotelike operators), and trailing modifiers are all caught.
528 For example, in:
529
530 extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #'
531
532 extract_quotelike ' "You said, \"Use sed\"." '
533
534 extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; '
535
536 extract_quotelike ' tr/\\\/\\\\/\\\//ds; '
537
538 the full Perl quotelike operations are all extracted correctly.
539
540 Note too that, when using the /x modifier on a regex, any comment
541 containing the current pattern delimiter will cause the regex to be
542 immediately terminated. In other words:
543
544 'm /
545 (?i) # CASE INSENSITIVE
546 [a-z_] # LEADING ALPHABETIC/UNDERSCORE
547 [a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS
548 /x'
549
550 will be extracted as if it were:
551
552 'm /
553 (?i) # CASE INSENSITIVE
554 [a-z_] # LEADING ALPHABETIC/'
555
556 This behaviour is identical to that of the actual compiler.
557
558 "extract_quotelike" takes two arguments: the text to be processed and a
559 prefix to be matched at the very beginning of the text. If no prefix is
560 specified, optional whitespace is the default. If no text is given, $_
561 is used.
562
563 In a list context, an array of 11 elements is returned. The elements
564 are:
565
566 [0] the extracted quotelike substring (including trailing modifiers),
567
568 [1] the remainder of the input text,
569
570 [2] the prefix substring (if any),
571
572 [3] the name of the quotelike operator (if any),
573
574 [4] the left delimiter of the first block of the operation,
575
576 [5] the text of the first block of the operation (that is, the contents
577 of a quote, the regex of a match or substitution or the target list
578 of a translation),
579
580 [6] the right delimiter of the first block of the operation,
581
582 [7] the left delimiter of the second block of the operation (that is,
583 if it is a "s", "tr", or "y"),
584
585 [8] the text of the second block of the operation (that is, the
586 replacement of a substitution or the translation list of a
587 translation),
588
589 [9] the right delimiter of the second block of the operation (if any),
590
591 [10]
592 the trailing modifiers on the operation (if any).
593
594 For each of the fields marked "(if any)" the default value on success
595 is an empty string. On failure, all of these values (except the
596 remaining text) are "undef".
597
598 In a scalar context, "extract_quotelike" returns just the complete
599 substring that matched a quotelike operation (or "undef" on failure).
600 In a scalar or void context, the input text has the same substring (and
601 any specified prefix) removed.
602
603 Examples:
604
605 # Remove the first quotelike literal that appears in text
606
607 $quotelike = extract_quotelike($text,'.*?');
608
609 # Replace one or more leading whitespace-separated quotelike
610 # literals in $_ with "<QLL>"
611
612 do { $_ = join '<QLL>', (extract_quotelike)[2,1] } until $@;
613
614
615 # Isolate the search pattern in a quotelike operation from $text
616
617 ($op,$pat) = (extract_quotelike $text)[3,5];
618 if ($op =~ /[ms]/)
619 {
620 print "search pattern: $pat\n";
621 }
622 else
623 {
624 print "$op is not a pattern matching operation\n";
625 }
626
627 "extract_quotelike" and "here documents"
628 "extract_quotelike" can successfully extract "here documents" from an
629 input string, but with an important caveat in list contexts.
630
631 Unlike other types of quote-like literals, a here document is rarely a
632 contiguous substring. For example, a typical piece of code using here
633 document might look like this:
634
635 <<'EOMSG' || die;
636 This is the message.
637 EOMSG
638 exit;
639
640 Given this as an input string in a scalar context, "extract_quotelike"
641 would correctly return the string "<<'EOMSG'\nThis is the
642 message.\nEOMSG", leaving the string " || die;\nexit;" in the original
643 variable. In other words, the two separate pieces of the here document
644 are successfully extracted and concatenated.
645
646 In a list context, "extract_quotelike" would return the list
647
648 [0] "<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted
649 here document, including fore and aft delimiters),
650
651 [1] " || die;\nexit;" (i.e. the remainder of the input text,
652 concatenated),
653
654 [2] "" (i.e. the prefix substring -- trivial in this case),
655
656 [3] "<<" (i.e. the "name" of the quotelike operator)
657
658 [4] "'EOMSG'" (i.e. the left delimiter of the here document, including
659 any quotes),
660
661 [5] "This is the message.\n" (i.e. the text of the here document),
662
663 [6] "EOMSG" (i.e. the right delimiter of the here document),
664
665 [7..10]
666 "" (a here document has no second left delimiter, second text,
667 second right delimiter, or trailing modifiers).
668
669 However, the matching position of the input variable would be set to
670 "exit;" (i.e. after the closing delimiter of the here document), which
671 would cause the earlier " || die;\nexit;" to be skipped in any sequence
672 of code fragment extractions.
673
674 To avoid this problem, when it encounters a here document whilst
675 extracting from a modifiable string, "extract_quotelike" silently
676 rearranges the string to an equivalent piece of Perl:
677
678 <<'EOMSG'
679 This is the message.
680 EOMSG
681 || die;
682 exit;
683
684 in which the here document is contiguous. It still leaves the matching
685 position after the here document, but now the rest of the line on which
686 the here document starts is not skipped.
687
688 To prevent <extract_quotelike> from mucking about with the input in
689 this way (this is the only case where a list-context
690 "extract_quotelike" does so), you can pass the input variable as an
691 interpolated literal:
692
693 $quotelike = extract_quotelike("$var");
694
695 "extract_codeblock"
696 "extract_codeblock" attempts to recognize and extract a balanced
697 bracket delimited substring that may contain unbalanced brackets inside
698 Perl quotes or quotelike operations. That is, "extract_codeblock" is
699 like a combination of "extract_bracketed" and "extract_quotelike".
700
701 "extract_codeblock" takes the same initial three parameters as
702 "extract_bracketed": a text to process, a set of delimiter brackets to
703 look for, and a prefix to match first. It also takes an optional fourth
704 parameter, which allows the outermost delimiter brackets to be
705 specified separately (see below).
706
707 Omitting the first argument (input text) means process $_ instead.
708 Omitting the second argument (delimiter brackets) indicates that only
709 '{' is to be used. Omitting the third argument (prefix argument)
710 implies optional whitespace at the start. Omitting the fourth argument
711 (outermost delimiter brackets) indicates that the value of the second
712 argument is to be used for the outermost delimiters.
713
714 Once the prefix an dthe outermost opening delimiter bracket have been
715 recognized, code blocks are extracted by stepping through the input
716 text and trying the following alternatives in sequence:
717
718 1. Try and match a closing delimiter bracket. If the bracket was the
719 same species as the last opening bracket, return the substring to
720 that point. If the bracket was mismatched, return an error.
721
722 2. Try to match a quote or quotelike operator. If found, call
723 "extract_quotelike" to eat it. If "extract_quotelike" fails, return
724 the error it returned. Otherwise go back to step 1.
725
726 3. Try to match an opening delimiter bracket. If found, call
727 "extract_codeblock" recursively to eat the embedded block. If the
728 recursive call fails, return an error. Otherwise, go back to step
729 1.
730
731 4. Unconditionally match a bareword or any other single character, and
732 then go back to step 1.
733
734 Examples:
735
736 # Find a while loop in the text
737
738 if ($text =~ s/.*?while\s*\{/{/)
739 {
740 $loop = "while " . extract_codeblock($text);
741 }
742
743 # Remove the first round-bracketed list (which may include
744 # round- or curly-bracketed code blocks or quotelike operators)
745
746 extract_codeblock $text, "(){}", '[^(]*';
747
748 The ability to specify a different outermost delimiter bracket is
749 useful in some circumstances. For example, in the Parse::RecDescent
750 module, parser actions which are to be performed only on a successful
751 parse are specified using a "<defer:...>" directive. For example:
752
753 sentence: subject verb object
754 <defer: {$::theVerb = $item{verb}} >
755
756 Parse::RecDescent uses "extract_codeblock($text, '{}<>')" to extract
757 the code within the "<defer:...>" directive, but there's a problem.
758
759 A deferred action like this:
760
761 <defer: {if ($count>10) {$count--}} >
762
763 will be incorrectly parsed as:
764
765 <defer: {if ($count>
766
767 because the "less than" operator is interpreted as a closing delimiter.
768
769 But, by extracting the directive using
770 "extract_codeblock($text, '{}', undef, '<>')" the '>' character is only
771 treated as a delimited at the outermost level of the code block, so the
772 directive is parsed correctly.
773
774 "extract_multiple"
775 The "extract_multiple" subroutine takes a string to be processed and a
776 list of extractors (subroutines or regular expressions) to apply to
777 that string.
778
779 In an array context "extract_multiple" returns an array of substrings
780 of the original string, as extracted by the specified extractors. In a
781 scalar context, "extract_multiple" returns the first substring
782 successfully extracted from the original string. In both scalar and
783 void contexts the original string has the first successfully extracted
784 substring removed from it. In all contexts "extract_multiple" starts at
785 the current "pos" of the string, and sets that "pos" appropriately
786 after it matches.
787
788 Hence, the aim of of a call to "extract_multiple" in a list context is
789 to split the processed string into as many non-overlapping fields as
790 possible, by repeatedly applying each of the specified extractors to
791 the remainder of the string. Thus "extract_multiple" is a generalized
792 form of Perl's "split" subroutine.
793
794 The subroutine takes up to four optional arguments:
795
796 1. A string to be processed ($_ if the string is omitted or "undef")
797
798 2. A reference to a list of subroutine references and/or qr// objects
799 and/or literal strings and/or hash references, specifying the
800 extractors to be used to split the string. If this argument is
801 omitted (or "undef") the list:
802
803 [
804 sub { extract_variable($_[0], '') },
805 sub { extract_quotelike($_[0],'') },
806 sub { extract_codeblock($_[0],'{}','') },
807 ]
808
809 is used.
810
811 3. An number specifying the maximum number of fields to return. If
812 this argument is omitted (or "undef"), split continues as long as
813 possible.
814
815 If the third argument is N, then extraction continues until N
816 fields have been successfully extracted, or until the string has
817 been completely processed.
818
819 Note that in scalar and void contexts the value of this argument is
820 automatically reset to 1 (under "-w", a warning is issued if the
821 argument has to be reset).
822
823 4. A value indicating whether unmatched substrings (see below) within
824 the text should be skipped or returned as fields. If the value is
825 true, such substrings are skipped. Otherwise, they are returned.
826
827 The extraction process works by applying each extractor in sequence to
828 the text string.
829
830 If the extractor is a subroutine it is called in a list context and is
831 expected to return a list of a single element, namely the extracted
832 text. It may optionally also return two further arguments: a string
833 representing the text left after extraction (like $' for a pattern
834 match), and a string representing any prefix skipped before the
835 extraction (like $` in a pattern match). Note that this is designed to
836 facilitate the use of other Text::Balanced subroutines with
837 "extract_multiple". Note too that the value returned by an extractor
838 subroutine need not bear any relationship to the corresponding
839 substring of the original text (see examples below).
840
841 If the extractor is a precompiled regular expression or a string, it is
842 matched against the text in a scalar context with a leading '\G' and
843 the gc modifiers enabled. The extracted value is either $1 if that
844 variable is defined after the match, or else the complete match (i.e.
845 $&).
846
847 If the extractor is a hash reference, it must contain exactly one
848 element. The value of that element is one of the above extractor types
849 (subroutine reference, regular expression, or string). The key of that
850 element is the name of a class into which the successful return value
851 of the extractor will be blessed.
852
853 If an extractor returns a defined value, that value is immediately
854 treated as the next extracted field and pushed onto the list of fields.
855 If the extractor was specified in a hash reference, the field is also
856 blessed into the appropriate class,
857
858 If the extractor fails to match (in the case of a regex extractor), or
859 returns an empty list or an undefined value (in the case of a
860 subroutine extractor), it is assumed to have failed to extract. If
861 none of the extractor subroutines succeeds, then one character is
862 extracted from the start of the text and the extraction subroutines
863 reapplied. Characters which are thus removed are accumulated and
864 eventually become the next field (unless the fourth argument is true,
865 in which case they are discarded).
866
867 For example, the following extracts substrings that are valid Perl
868 variables:
869
870 @fields = extract_multiple($text,
871 [ sub { extract_variable($_[0]) } ],
872 undef, 1);
873
874 This example separates a text into fields which are quote delimited,
875 curly bracketed, and anything else. The delimited and bracketed parts
876 are also blessed to identify them (the "anything else" is unblessed):
877
878 @fields = extract_multiple($text,
879 [
880 { Delim => sub { extract_delimited($_[0],q{'"}) } },
881 { Brack => sub { extract_bracketed($_[0],'{}') } },
882 ]);
883
884 This call extracts the next single substring that is a valid Perl
885 quotelike operator (and removes it from $text):
886
887 $quotelike = extract_multiple($text,
888 [
889 sub { extract_quotelike($_[0]) },
890 ], undef, 1);
891
892 Finally, here is yet another way to do comma-separated value parsing:
893
894 @fields = extract_multiple($csv_text,
895 [
896 sub { extract_delimited($_[0],q{'"}) },
897 qr/([^,]+)(.*)/,
898 ],
899 undef,1);
900
901 The list in the second argument means: "Try and extract a ' or "
902 delimited string, otherwise extract anything up to a comma...". The
903 undef third argument means: "...as many times as possible...", and the
904 true value in the fourth argument means "...discarding anything else
905 that appears (i.e. the commas)".
906
907 If you wanted the commas preserved as separate fields (i.e. like split
908 does if your split pattern has capturing parentheses), you would just
909 make the last parameter undefined (or remove it).
910
911 "gen_delimited_pat"
912 The "gen_delimited_pat" subroutine takes a single (string) argument and
913 > builds a Friedl-style optimized regex that matches a string
914 delimited by any one of the characters in the single argument. For
915 example:
916
917 gen_delimited_pat(q{'"})
918
919 returns the regex:
920
921 (?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\')
922
923 Note that the specified delimiters are automatically quotemeta'd.
924
925 A typical use of "gen_delimited_pat" would be to build special purpose
926 tags for "extract_tagged". For example, to properly ignore "empty" XML
927 elements (which might contain quoted strings):
928
929 my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>';
930
931 extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} );
932
933 "gen_delimited_pat" may also be called with an optional second
934 argument, which specifies the "escape" character(s) to be used for each
935 delimiter. For example to match a Pascal-style string (where ' is the
936 delimiter and '' is a literal ' within the string):
937
938 gen_delimited_pat(q{'},q{'});
939
940 Different escape characters can be specified for different delimiters.
941 For example, to specify that '/' is the escape for single quotes and
942 '%' is the escape for double quotes:
943
944 gen_delimited_pat(q{'"},q{/%});
945
946 If more delimiters than escape chars are specified, the last escape
947 char is used for the remaining delimiters. If no escape char is
948 specified for a given specified delimiter, '\' is used.
949
950 "delimited_pat"
951 Note that "gen_delimited_pat" was previously called "delimited_pat".
952 That name may still be used, but is now deprecated.
953
955 In a list context, all the functions return "(undef,$original_text)" on
956 failure. In a scalar context, failure is indicated by returning "undef"
957 (in this case the input text is not modified in any way).
958
959 In addition, on failure in any context, the $@ variable is set.
960 Accessing "$@->{error}" returns one of the error diagnostics listed
961 below. Accessing "$@->{pos}" returns the offset into the original
962 string at which the error was detected (although not necessarily where
963 it occurred!) Printing $@ directly produces the error message, with
964 the offset appended. On success, the $@ variable is guaranteed to be
965 "undef".
966
967 The available diagnostics are:
968
969 "Did not find a suitable bracket: "%s""
970 The delimiter provided to "extract_bracketed" was not one of
971 '()[]<>{}'.
972
973 "Did not find prefix: /%s/"
974 A non-optional prefix was specified but wasn't found at the start
975 of the text.
976
977 "Did not find opening bracket after prefix: "%s""
978 "extract_bracketed" or "extract_codeblock" was expecting a
979 particular kind of bracket at the start of the text, and didn't
980 find it.
981
982 "No quotelike operator found after prefix: "%s""
983 "extract_quotelike" didn't find one of the quotelike operators "q",
984 "qq", "qw", "qx", "s", "tr" or "y" at the start of the substring it
985 was extracting.
986
987 "Unmatched closing bracket: "%c""
988 "extract_bracketed", "extract_quotelike" or "extract_codeblock"
989 encountered a closing bracket where none was expected.
990
991 "Unmatched opening bracket(s): "%s""
992 "extract_bracketed", "extract_quotelike" or "extract_codeblock" ran
993 out of characters in the text before closing one or more levels of
994 nested brackets.
995
996 "Unmatched embedded quote (%s)"
997 "extract_bracketed" attempted to match an embedded quoted
998 substring, but failed to find a closing quote to match it.
999
1000 "Did not find closing delimiter to match '%s'"
1001 "extract_quotelike" was unable to find a closing delimiter to match
1002 the one that opened the quote-like operation.
1003
1004 "Mismatched closing bracket: expected "%c" but found "%s""
1005 "extract_bracketed", "extract_quotelike" or "extract_codeblock"
1006 found a valid bracket delimiter, but it was the wrong species. This
1007 usually indicates a nesting error, but may indicate incorrect
1008 quoting or escaping.
1009
1010 "No block delimiter found after quotelike "%s""
1011 "extract_quotelike" or "extract_codeblock" found one of the
1012 quotelike operators "q", "qq", "qw", "qx", "s", "tr" or "y" without
1013 a suitable block after it.
1014
1015 "Did not find leading dereferencer"
1016 "extract_variable" was expecting one of '$', '@', or '%' at the
1017 start of a variable, but didn't find any of them.
1018
1019 "Bad identifier after dereferencer"
1020 "extract_variable" found a '$', '@', or '%' indicating a variable,
1021 but that character was not followed by a legal Perl identifier.
1022
1023 "Did not find expected opening bracket at %s"
1024 "extract_codeblock" failed to find any of the outermost opening
1025 brackets that were specified.
1026
1027 "Improperly nested codeblock at %s"
1028 A nested code block was found that started with a delimiter that
1029 was specified as being only to be used as an outermost bracket.
1030
1031 "Missing second block for quotelike "%s""
1032 "extract_codeblock" or "extract_quotelike" found one of the
1033 quotelike operators "s", "tr" or "y" followed by only one block.
1034
1035 "No match found for opening bracket"
1036 "extract_codeblock" failed to find a closing bracket to match the
1037 outermost opening bracket.
1038
1039 "Did not find opening tag: /%s/"
1040 "extract_tagged" did not find a suitable opening tag (after any
1041 specified prefix was removed).
1042
1043 "Unable to construct closing tag to match: /%s/"
1044 "extract_tagged" matched the specified opening tag and tried to
1045 modify the matched text to produce a matching closing tag (because
1046 none was specified). It failed to generate the closing tag, almost
1047 certainly because the opening tag did not start with a bracket of
1048 some kind.
1049
1050 "Found invalid nested tag: %s"
1051 "extract_tagged" found a nested tag that appeared in the "reject"
1052 list (and the failure mode was not "MAX" or "PARA").
1053
1054 "Found unbalanced nested tag: %s"
1055 "extract_tagged" found a nested opening tag that was not matched by
1056 a corresponding nested closing tag (and the failure mode was not
1057 "MAX" or "PARA").
1058
1059 "Did not find closing tag"
1060 "extract_tagged" reached the end of the text without finding a
1061 closing tag to match the original opening tag (and the failure mode
1062 was not "MAX" or "PARA").
1063
1065 Damian Conway (damian@conway.org)
1066
1068 There are undoubtedly serious bugs lurking somewhere in this code, if
1069 only because parts of it give the impression of understanding a great
1070 deal more about Perl than they really do.
1071
1072 Bug reports and other feedback are most welcome.
1073
1075 Copyright (c) 1997-2001, Damian Conway. All Rights Reserved.
1076 This module is free software. It may be used, redistributed
1077 and/or modified under the same terms as Perl itself.
1078
1079
1080
1081perl v5.10.1 2009-02-25 Text::Balanced(3pm)