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