diff options
author | Siep Kroonenberg <siepo@cybercomm.nl> | 2011-02-17 12:20:49 +0000 |
---|---|---|
committer | Siep Kroonenberg <siepo@cybercomm.nl> | 2011-02-17 12:20:49 +0000 |
commit | 316ee97c621496b0fe3267f57cce81bee44ca1e6 (patch) | |
tree | cb2cab1192b4f58a7971af19b213e980bceda4b4 /Master/tlpkg/tlperl/lib/Text | |
parent | cd0f87b5d39480d85ad9bd4ee37f520f75bed560 (diff) |
Moving old tlperl prior to committing new one
git-svn-id: svn://tug.org/texlive/trunk@21422 c570f23f-e606-0410-a88d-b1316a301751
Diffstat (limited to 'Master/tlpkg/tlperl/lib/Text')
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Abbrev.pm | 84 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Balanced.pm | 2281 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Diff.pm | 713 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Diff/Table.pm | 408 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Glob.pm | 195 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/ParseWords.pm | 294 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Soundex.pm | 260 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Tabs.pm | 136 | ||||
-rwxr-xr-x | Master/tlpkg/tlperl/lib/Text/Wrap.pm | 265 |
9 files changed, 0 insertions, 4636 deletions
diff --git a/Master/tlpkg/tlperl/lib/Text/Abbrev.pm b/Master/tlpkg/tlperl/lib/Text/Abbrev.pm deleted file mode 100755 index c6be63bcc60..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Abbrev.pm +++ /dev/null @@ -1,84 +0,0 @@ -package Text::Abbrev; -require 5.005; # Probably works on earlier versions too. -require Exporter; - -our $VERSION = '1.01'; - -=head1 NAME - -abbrev - create an abbreviation table from a list - -=head1 SYNOPSIS - - use Text::Abbrev; - abbrev $hashref, LIST - - -=head1 DESCRIPTION - -Stores all unambiguous truncations of each element of LIST -as keys in the associative array referenced by C<$hashref>. -The values are the original list elements. - -=head1 EXAMPLE - - $hashref = abbrev qw(list edit send abort gripe); - - %hash = abbrev qw(list edit send abort gripe); - - abbrev $hashref, qw(list edit send abort gripe); - - abbrev(*hash, qw(list edit send abort gripe)); - -=cut - -@ISA = qw(Exporter); -@EXPORT = qw(abbrev); - -# Usage: -# abbrev \%foo, LIST; -# ... -# $long = $foo{$short}; - -sub abbrev { - my ($word, $hashref, $glob, %table, $returnvoid); - - @_ or return; # So we don't autovivify onto @_ and trigger warning - if (ref($_[0])) { # hash reference preferably - $hashref = shift; - $returnvoid = 1; - } elsif (ref \$_[0] eq 'GLOB') { # is actually a glob (deprecated) - $hashref = \%{shift()}; - $returnvoid = 1; - } - %{$hashref} = (); - - WORD: foreach $word (@_) { - for (my $len = (length $word) - 1; $len > 0; --$len) { - my $abbrev = substr($word,0,$len); - my $seen = ++$table{$abbrev}; - if ($seen == 1) { # We're the first word so far to have - # this abbreviation. - $hashref->{$abbrev} = $word; - } elsif ($seen == 2) { # We're the second word to have this - # abbreviation, so we can't use it. - delete $hashref->{$abbrev}; - } else { # We're the third word to have this - # abbreviation, so skip to the next word. - next WORD; - } - } - } - # Non-abbreviations always get entered, even if they aren't unique - foreach $word (@_) { - $hashref->{$word} = $word; - } - return if $returnvoid; - if (wantarray) { - %{$hashref}; - } else { - $hashref; - } -} - -1; diff --git a/Master/tlpkg/tlperl/lib/Text/Balanced.pm b/Master/tlpkg/tlperl/lib/Text/Balanced.pm deleted file mode 100755 index 07d956735c2..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Balanced.pm +++ /dev/null @@ -1,2281 +0,0 @@ -package Text::Balanced; - -# EXTRACT VARIOUSLY DELIMITED TEXT SEQUENCES FROM STRINGS. -# FOR FULL DOCUMENTATION SEE Balanced.pod - -use 5.005; -use strict; -use Exporter (); -use SelfLoader; - -use vars qw { $VERSION @ISA %EXPORT_TAGS }; -BEGIN { - $VERSION = '2.02'; - @ISA = 'Exporter'; - %EXPORT_TAGS = ( - ALL => [ qw{ - &extract_delimited - &extract_bracketed - &extract_quotelike - &extract_codeblock - &extract_variable - &extract_tagged - &extract_multiple - &gen_delimited_pat - &gen_extract_tagged - &delimited_pat - } ], - ); -} - -Exporter::export_ok_tags('ALL'); - -# PROTOTYPES - -sub _match_bracketed($$$$$$); -sub _match_variable($$); -sub _match_codeblock($$$$$$$); -sub _match_quotelike($$$$); - -# HANDLE RETURN VALUES IN VARIOUS CONTEXTS - -sub _failmsg { - my ($message, $pos) = @_; - $@ = bless { - error => $message, - pos => $pos, - }, 'Text::Balanced::ErrorMsg'; -} - -sub _fail { - my ($wantarray, $textref, $message, $pos) = @_; - _failmsg $message, $pos if $message; - return (undef, $$textref, undef) if $wantarray; - return undef; -} - -sub _succeed { - $@ = undef; - my ($wantarray,$textref) = splice @_, 0, 2; - my ($extrapos, $extralen) = @_ > 18 - ? splice(@_, -2, 2) - : (0, 0); - my ($startlen, $oppos) = @_[5,6]; - my $remainderpos = $_[2]; - if ( $wantarray ) { - my @res; - while (my ($from, $len) = splice @_, 0, 2) { - push @res, substr($$textref, $from, $len); - } - if ( $extralen ) { # CORRECT FILLET - my $extra = substr($res[0], $extrapos-$oppos, $extralen, "\n"); - $res[1] = "$extra$res[1]"; - eval { substr($$textref,$remainderpos,0) = $extra; - substr($$textref,$extrapos,$extralen,"\n")} ; - #REARRANGE HERE DOC AND FILLET IF POSSIBLE - pos($$textref) = $remainderpos-$extralen+1; # RESET \G - } else { - pos($$textref) = $remainderpos; # RESET \G - } - return @res; - } else { - my $match = substr($$textref,$_[0],$_[1]); - substr($match,$extrapos-$_[0]-$startlen,$extralen,"") if $extralen; - my $extra = $extralen - ? substr($$textref, $extrapos, $extralen)."\n" : ""; - eval {substr($$textref,$_[4],$_[1]+$_[5])=$extra} ; #CHOP OUT PREFIX & MATCH, IF POSSIBLE - pos($$textref) = $_[4]; # RESET \G - return $match; - } -} - -# BUILD A PATTERN MATCHING A SIMPLE DELIMITED STRING - -sub gen_delimited_pat($;$) # ($delimiters;$escapes) -{ - my ($dels, $escs) = @_; - return "" unless $dels =~ /\S/; - $escs = '\\' unless $escs; - $escs .= substr($escs,-1) x (length($dels)-length($escs)); - my @pat = (); - my $i; - for ($i=0; $i<length $dels; $i++) - { - my $del = quotemeta substr($dels,$i,1); - my $esc = quotemeta substr($escs,$i,1); - if ($del eq $esc) - { - push @pat, "$del(?:[^$del]*(?:(?:$del$del)[^$del]*)*)$del"; - } - else - { - push @pat, "$del(?:[^$esc$del]*(?:$esc.[^$esc$del]*)*)$del"; - } - } - my $pat = join '|', @pat; - return "(?:$pat)"; -} - -*delimited_pat = \&gen_delimited_pat; - -# THE EXTRACTION FUNCTIONS - -sub extract_delimited (;$$$$) -{ - my $textref = defined $_[0] ? \$_[0] : \$_; - my $wantarray = wantarray; - my $del = defined $_[1] ? $_[1] : qq{\'\"\`}; - my $pre = defined $_[2] ? $_[2] : '\s*'; - my $esc = defined $_[3] ? $_[3] : qq{\\}; - my $pat = gen_delimited_pat($del, $esc); - my $startpos = pos $$textref || 0; - return _fail($wantarray, $textref, "Not a delimited pattern", 0) - unless $$textref =~ m/\G($pre)($pat)/gc; - my $prelen = length($1); - my $matchpos = $startpos+$prelen; - my $endpos = pos $$textref; - return _succeed $wantarray, $textref, - $matchpos, $endpos-$matchpos, # MATCH - $endpos, length($$textref)-$endpos, # REMAINDER - $startpos, $prelen; # PREFIX -} - -sub extract_bracketed (;$$$) -{ - my $textref = defined $_[0] ? \$_[0] : \$_; - my $ldel = defined $_[1] ? $_[1] : '{([<'; - my $pre = defined $_[2] ? $_[2] : '\s*'; - my $wantarray = wantarray; - my $qdel = ""; - my $quotelike; - $ldel =~ s/'//g and $qdel .= q{'}; - $ldel =~ s/"//g and $qdel .= q{"}; - $ldel =~ s/`//g and $qdel .= q{`}; - $ldel =~ s/q//g and $quotelike = 1; - $ldel =~ tr/[](){}<>\0-\377/[[(({{<</ds; - my $rdel = $ldel; - unless ($rdel =~ tr/[({</])}>/) - { - return _fail $wantarray, $textref, - "Did not find a suitable bracket in delimiter: \"$_[1]\"", - 0; - } - my $posbug = pos; - $ldel = join('|', map { quotemeta $_ } split('', $ldel)); - $rdel = join('|', map { quotemeta $_ } split('', $rdel)); - pos = $posbug; - - my $startpos = pos $$textref || 0; - my @match = _match_bracketed($textref,$pre, $ldel, $qdel, $quotelike, $rdel); - - return _fail ($wantarray, $textref) unless @match; - - return _succeed ( $wantarray, $textref, - $match[2], $match[5]+2, # MATCH - @match[8,9], # REMAINDER - @match[0,1], # PREFIX - ); -} - -sub _match_bracketed($$$$$$) # $textref, $pre, $ldel, $qdel, $quotelike, $rdel -{ - my ($textref, $pre, $ldel, $qdel, $quotelike, $rdel) = @_; - my ($startpos, $ldelpos, $endpos) = (pos $$textref = pos $$textref||0); - unless ($$textref =~ m/\G$pre/gc) - { - _failmsg "Did not find prefix: /$pre/", $startpos; - return; - } - - $ldelpos = pos $$textref; - - unless ($$textref =~ m/\G($ldel)/gc) - { - _failmsg "Did not find opening bracket after prefix: \"$pre\"", - pos $$textref; - pos $$textref = $startpos; - return; - } - - my @nesting = ( $1 ); - my $textlen = length $$textref; - while (pos $$textref < $textlen) - { - next if $$textref =~ m/\G\\./gcs; - - if ($$textref =~ m/\G($ldel)/gc) - { - push @nesting, $1; - } - elsif ($$textref =~ m/\G($rdel)/gc) - { - my ($found, $brackettype) = ($1, $1); - if ($#nesting < 0) - { - _failmsg "Unmatched closing bracket: \"$found\"", - pos $$textref; - pos $$textref = $startpos; - return; - } - my $expected = pop(@nesting); - $expected =~ tr/({[</)}]>/; - if ($expected ne $brackettype) - { - _failmsg qq{Mismatched closing bracket: expected "$expected" but found "$found"}, - pos $$textref; - pos $$textref = $startpos; - return; - } - last if $#nesting < 0; - } - elsif ($qdel && $$textref =~ m/\G([$qdel])/gc) - { - $$textref =~ m/\G[^\\$1]*(?:\\.[^\\$1]*)*(\Q$1\E)/gsc and next; - _failmsg "Unmatched embedded quote ($1)", - pos $$textref; - pos $$textref = $startpos; - return; - } - elsif ($quotelike && _match_quotelike($textref,"",1,0)) - { - next; - } - - else { $$textref =~ m/\G(?:[a-zA-Z0-9]+|.)/gcs } - } - if ($#nesting>=0) - { - _failmsg "Unmatched opening bracket(s): " - . join("..",@nesting)."..", - pos $$textref; - pos $$textref = $startpos; - return; - } - - $endpos = pos $$textref; - - return ( - $startpos, $ldelpos-$startpos, # PREFIX - $ldelpos, 1, # OPENING BRACKET - $ldelpos+1, $endpos-$ldelpos-2, # CONTENTS - $endpos-1, 1, # CLOSING BRACKET - $endpos, length($$textref)-$endpos, # REMAINDER - ); -} - -sub _revbracket($) -{ - my $brack = reverse $_[0]; - $brack =~ tr/[({</])}>/; - return $brack; -} - -my $XMLNAME = q{[a-zA-Z_:][a-zA-Z0-9_:.-]*}; - -sub extract_tagged (;$$$$$) # ($text, $opentag, $closetag, $pre, \%options) -{ - my $textref = defined $_[0] ? \$_[0] : \$_; - my $ldel = $_[1]; - my $rdel = $_[2]; - my $pre = defined $_[3] ? $_[3] : '\s*'; - my %options = defined $_[4] ? %{$_[4]} : (); - my $omode = defined $options{fail} ? $options{fail} : ''; - my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}}) - : defined($options{reject}) ? $options{reject} - : '' - ; - my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}}) - : defined($options{ignore}) ? $options{ignore} - : '' - ; - - if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; } - $@ = undef; - - my @match = _match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore); - - return _fail(wantarray, $textref) unless @match; - return _succeed wantarray, $textref, - $match[2], $match[3]+$match[5]+$match[7], # MATCH - @match[8..9,0..1,2..7]; # REM, PRE, BITS -} - -sub _match_tagged # ($$$$$$$) -{ - my ($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore) = @_; - my $rdelspec; - - my ($startpos, $opentagpos, $textpos, $parapos, $closetagpos, $endpos) = ( pos($$textref) = pos($$textref)||0 ); - - unless ($$textref =~ m/\G($pre)/gc) - { - _failmsg "Did not find prefix: /$pre/", pos $$textref; - goto failed; - } - - $opentagpos = pos($$textref); - - unless ($$textref =~ m/\G$ldel/gc) - { - _failmsg "Did not find opening tag: /$ldel/", pos $$textref; - goto failed; - } - - $textpos = pos($$textref); - - if (!defined $rdel) - { - $rdelspec = substr($$textref, $-[0], $+[0] - $-[0]); - unless ($rdelspec =~ s/\A([[(<{]+)($XMLNAME).*/ quotemeta "$1\/$2". _revbracket($1) /oes) - { - _failmsg "Unable to construct closing tag to match: $rdel", - pos $$textref; - goto failed; - } - } - else - { - $rdelspec = eval "qq{$rdel}" || do { - my $del; - for (qw,~ ! ^ & * ) _ + - = } ] : " ; ' > . ? / | ',) - { next if $rdel =~ /\Q$_/; $del = $_; last } - unless ($del) { - use Carp; - croak "Can't interpolate right delimiter $rdel" - } - eval "qq$del$rdel$del"; - }; - } - - while (pos($$textref) < length($$textref)) - { - next if $$textref =~ m/\G\\./gc; - - if ($$textref =~ m/\G(\n[ \t]*\n)/gc ) - { - $parapos = pos($$textref) - length($1) - unless defined $parapos; - } - elsif ($$textref =~ m/\G($rdelspec)/gc ) - { - $closetagpos = pos($$textref)-length($1); - goto matched; - } - elsif ($ignore && $$textref =~ m/\G(?:$ignore)/gc) - { - next; - } - elsif ($bad && $$textref =~ m/\G($bad)/gcs) - { - pos($$textref) -= length($1); # CUT OFF WHATEVER CAUSED THE SHORTNESS - goto short if ($omode eq 'PARA' || $omode eq 'MAX'); - _failmsg "Found invalid nested tag: $1", pos $$textref; - goto failed; - } - elsif ($$textref =~ m/\G($ldel)/gc) - { - my $tag = $1; - pos($$textref) -= length($tag); # REWIND TO NESTED TAG - unless (_match_tagged(@_)) # MATCH NESTED TAG - { - goto short if $omode eq 'PARA' || $omode eq 'MAX'; - _failmsg "Found unbalanced nested tag: $tag", - pos $$textref; - goto failed; - } - } - else { $$textref =~ m/./gcs } - } - -short: - $closetagpos = pos($$textref); - goto matched if $omode eq 'MAX'; - goto failed unless $omode eq 'PARA'; - - if (defined $parapos) { pos($$textref) = $parapos } - else { $parapos = pos($$textref) } - - return ( - $startpos, $opentagpos-$startpos, # PREFIX - $opentagpos, $textpos-$opentagpos, # OPENING TAG - $textpos, $parapos-$textpos, # TEXT - $parapos, 0, # NO CLOSING TAG - $parapos, length($$textref)-$parapos, # REMAINDER - ); - -matched: - $endpos = pos($$textref); - return ( - $startpos, $opentagpos-$startpos, # PREFIX - $opentagpos, $textpos-$opentagpos, # OPENING TAG - $textpos, $closetagpos-$textpos, # TEXT - $closetagpos, $endpos-$closetagpos, # CLOSING TAG - $endpos, length($$textref)-$endpos, # REMAINDER - ); - -failed: - _failmsg "Did not find closing tag", pos $$textref unless $@; - pos($$textref) = $startpos; - return; -} - -sub extract_variable (;$$) -{ - my $textref = defined $_[0] ? \$_[0] : \$_; - return ("","","") unless defined $$textref; - my $pre = defined $_[1] ? $_[1] : '\s*'; - - my @match = _match_variable($textref,$pre); - - return _fail wantarray, $textref unless @match; - - return _succeed wantarray, $textref, - @match[2..3,4..5,0..1]; # MATCH, REMAINDER, PREFIX -} - -sub _match_variable($$) -{ -# $# -# $^ -# $$ - my ($textref, $pre) = @_; - my $startpos = pos($$textref) = pos($$textref)||0; - unless ($$textref =~ m/\G($pre)/gc) - { - _failmsg "Did not find prefix: /$pre/", pos $$textref; - return; - } - my $varpos = pos($$textref); - unless ($$textref =~ m{\G\$\s*(?!::)(\d+|[][&`'+*./|,";%=~:?!\@<>()-]|\^[a-z]?)}gci) - { - unless ($$textref =~ m/\G((\$#?|[*\@\%]|\\&)+)/gc) - { - _failmsg "Did not find leading dereferencer", pos $$textref; - pos $$textref = $startpos; - return; - } - my $deref = $1; - - unless ($$textref =~ m/\G\s*(?:::|')?(?:[_a-z]\w*(?:::|'))*[_a-z]\w*/gci - or _match_codeblock($textref, "", '\{', '\}', '\{', '\}', 0) - or $deref eq '$#' or $deref eq '$$' ) - { - _failmsg "Bad identifier after dereferencer", pos $$textref; - pos $$textref = $startpos; - return; - } - } - - while (1) - { - next if $$textref =~ m/\G\s*(?:->)?\s*[{]\w+[}]/gc; - next if _match_codeblock($textref, - qr/\s*->\s*(?:[_a-zA-Z]\w+\s*)?/, - qr/[({[]/, qr/[)}\]]/, - qr/[({[]/, qr/[)}\]]/, 0); - next if _match_codeblock($textref, - qr/\s*/, qr/[{[]/, qr/[}\]]/, - qr/[{[]/, qr/[}\]]/, 0); - next if _match_variable($textref,'\s*->\s*'); - next if $$textref =~ m/\G\s*->\s*\w+(?![{([])/gc; - last; - } - - my $endpos = pos($$textref); - return ($startpos, $varpos-$startpos, - $varpos, $endpos-$varpos, - $endpos, length($$textref)-$endpos - ); -} - -sub extract_codeblock (;$$$$$) -{ - my $textref = defined $_[0] ? \$_[0] : \$_; - my $wantarray = wantarray; - my $ldel_inner = defined $_[1] ? $_[1] : '{'; - my $pre = defined $_[2] ? $_[2] : '\s*'; - my $ldel_outer = defined $_[3] ? $_[3] : $ldel_inner; - my $rd = $_[4]; - my $rdel_inner = $ldel_inner; - my $rdel_outer = $ldel_outer; - my $posbug = pos; - for ($ldel_inner, $ldel_outer) { tr/[]()<>{}\0-\377/[[((<<{{/ds } - for ($rdel_inner, $rdel_outer) { tr/[]()<>{}\0-\377/]]))>>}}/ds } - for ($ldel_inner, $ldel_outer, $rdel_inner, $rdel_outer) - { - $_ = '('.join('|',map { quotemeta $_ } split('',$_)).')' - } - pos = $posbug; - - my @match = _match_codeblock($textref, $pre, - $ldel_outer, $rdel_outer, - $ldel_inner, $rdel_inner, - $rd); - return _fail($wantarray, $textref) unless @match; - return _succeed($wantarray, $textref, - @match[2..3,4..5,0..1] # MATCH, REMAINDER, PREFIX - ); - -} - -sub _match_codeblock($$$$$$$) -{ - my ($textref, $pre, $ldel_outer, $rdel_outer, $ldel_inner, $rdel_inner, $rd) = @_; - my $startpos = pos($$textref) = pos($$textref) || 0; - unless ($$textref =~ m/\G($pre)/gc) - { - _failmsg qq{Did not match prefix /$pre/ at"} . - substr($$textref,pos($$textref),20) . - q{..."}, - pos $$textref; - return; - } - my $codepos = pos($$textref); - unless ($$textref =~ m/\G($ldel_outer)/gc) # OUTERMOST DELIMITER - { - _failmsg qq{Did not find expected opening bracket at "} . - substr($$textref,pos($$textref),20) . - q{..."}, - pos $$textref; - pos $$textref = $startpos; - return; - } - my $closing = $1; - $closing =~ tr/([<{/)]>}/; - my $matched; - my $patvalid = 1; - while (pos($$textref) < length($$textref)) - { - $matched = ''; - if ($rd && $$textref =~ m#\G(\Q(?)\E|\Q(s?)\E|\Q(s)\E)#gc) - { - $patvalid = 0; - next; - } - - if ($$textref =~ m/\G\s*#.*/gc) - { - next; - } - - if ($$textref =~ m/\G\s*($rdel_outer)/gc) - { - unless ($matched = ($closing && $1 eq $closing) ) - { - next if $1 eq '>'; # MIGHT BE A "LESS THAN" - _failmsg q{Mismatched closing bracket at "} . - substr($$textref,pos($$textref),20) . - qq{...". Expected '$closing'}, - pos $$textref; - } - last; - } - - if (_match_variable($textref,'\s*') || - _match_quotelike($textref,'\s*',$patvalid,$patvalid) ) - { - $patvalid = 0; - next; - } - - - # NEED TO COVER MANY MORE CASES HERE!!! - if ($$textref =~ m#\G\s*(?!$ldel_inner) - ( [-+*x/%^&|.]=? - | [!=]~ - | =(?!>) - | (\*\*|&&|\|\||<<|>>)=? - | split|grep|map|return - | [([] - )#gcx) - { - $patvalid = 1; - next; - } - - if ( _match_codeblock($textref, '\s*', $ldel_inner, $rdel_inner, $ldel_inner, $rdel_inner, $rd) ) - { - $patvalid = 1; - next; - } - - if ($$textref =~ m/\G\s*$ldel_outer/gc) - { - _failmsg q{Improperly nested codeblock at "} . - substr($$textref,pos($$textref),20) . - q{..."}, - pos $$textref; - last; - } - - $patvalid = 0; - $$textref =~ m/\G\s*(\w+|[-=>]>|.|\Z)/gc; - } - continue { $@ = undef } - - unless ($matched) - { - _failmsg 'No match found for opening bracket', pos $$textref - unless $@; - return; - } - - my $endpos = pos($$textref); - return ( $startpos, $codepos-$startpos, - $codepos, $endpos-$codepos, - $endpos, length($$textref)-$endpos, - ); -} - - -my %mods = ( - 'none' => '[cgimsox]*', - 'm' => '[cgimsox]*', - 's' => '[cegimsox]*', - 'tr' => '[cds]*', - 'y' => '[cds]*', - 'qq' => '', - 'qx' => '', - 'qw' => '', - 'qr' => '[imsx]*', - 'q' => '', - ); - -sub extract_quotelike (;$$) -{ - my $textref = $_[0] ? \$_[0] : \$_; - my $wantarray = wantarray; - my $pre = defined $_[1] ? $_[1] : '\s*'; - - my @match = _match_quotelike($textref,$pre,1,0); - return _fail($wantarray, $textref) unless @match; - return _succeed($wantarray, $textref, - $match[2], $match[18]-$match[2], # MATCH - @match[18,19], # REMAINDER - @match[0,1], # PREFIX - @match[2..17], # THE BITS - @match[20,21], # ANY FILLET? - ); -}; - -sub _match_quotelike($$$$) # ($textref, $prepat, $allow_raw_match) -{ - my ($textref, $pre, $rawmatch, $qmark) = @_; - - my ($textlen,$startpos, - $oppos, - $preld1pos,$ld1pos,$str1pos,$rd1pos, - $preld2pos,$ld2pos,$str2pos,$rd2pos, - $modpos) = ( length($$textref), pos($$textref) = pos($$textref) || 0 ); - - unless ($$textref =~ m/\G($pre)/gc) - { - _failmsg qq{Did not find prefix /$pre/ at "} . - substr($$textref, pos($$textref), 20) . - q{..."}, - pos $$textref; - return; - } - $oppos = pos($$textref); - - my $initial = substr($$textref,$oppos,1); - - if ($initial && $initial =~ m|^[\"\'\`]| - || $rawmatch && $initial =~ m|^/| - || $qmark && $initial =~ m|^\?|) - { - unless ($$textref =~ m/ \Q$initial\E [^\\$initial]* (\\.[^\\$initial]*)* \Q$initial\E /gcsx) - { - _failmsg qq{Did not find closing delimiter to match '$initial' at "} . - substr($$textref, $oppos, 20) . - q{..."}, - pos $$textref; - pos $$textref = $startpos; - return; - } - $modpos= pos($$textref); - $rd1pos = $modpos-1; - - if ($initial eq '/' || $initial eq '?') - { - $$textref =~ m/\G$mods{none}/gc - } - - my $endpos = pos($$textref); - return ( - $startpos, $oppos-$startpos, # PREFIX - $oppos, 0, # NO OPERATOR - $oppos, 1, # LEFT DEL - $oppos+1, $rd1pos-$oppos-1, # STR/PAT - $rd1pos, 1, # RIGHT DEL - $modpos, 0, # NO 2ND LDEL - $modpos, 0, # NO 2ND STR - $modpos, 0, # NO 2ND RDEL - $modpos, $endpos-$modpos, # MODIFIERS - $endpos, $textlen-$endpos, # REMAINDER - ); - } - - unless ($$textref =~ m{\G(\b(?:m|s|qq|qx|qw|q|qr|tr|y)\b(?=\s*\S)|<<)}gc) - { - _failmsg q{No quotelike operator found after prefix at "} . - substr($$textref, pos($$textref), 20) . - q{..."}, - pos $$textref; - pos $$textref = $startpos; - return; - } - - my $op = $1; - $preld1pos = pos($$textref); - if ($op eq '<<') { - $ld1pos = pos($$textref); - my $label; - if ($$textref =~ m{\G([A-Za-z_]\w*)}gc) { - $label = $1; - } - elsif ($$textref =~ m{ \G ' ([^'\\]* (?:\\.[^'\\]*)*) ' - | \G " ([^"\\]* (?:\\.[^"\\]*)*) " - | \G ` ([^`\\]* (?:\\.[^`\\]*)*) ` - }gcsx) { - $label = $+; - } - else { - $label = ""; - } - my $extrapos = pos($$textref); - $$textref =~ m{.*\n}gc; - $str1pos = pos($$textref)--; - unless ($$textref =~ m{.*?\n(?=\Q$label\E\n)}gc) { - _failmsg qq{Missing here doc terminator ('$label') after "} . - substr($$textref, $startpos, 20) . - q{..."}, - pos $$textref; - pos $$textref = $startpos; - return; - } - $rd1pos = pos($$textref); - $$textref =~ m{\Q$label\E\n}gc; - $ld2pos = pos($$textref); - return ( - $startpos, $oppos-$startpos, # PREFIX - $oppos, length($op), # OPERATOR - $ld1pos, $extrapos-$ld1pos, # LEFT DEL - $str1pos, $rd1pos-$str1pos, # STR/PAT - $rd1pos, $ld2pos-$rd1pos, # RIGHT DEL - $ld2pos, 0, # NO 2ND LDEL - $ld2pos, 0, # NO 2ND STR - $ld2pos, 0, # NO 2ND RDEL - $ld2pos, 0, # NO MODIFIERS - $ld2pos, $textlen-$ld2pos, # REMAINDER - $extrapos, $str1pos-$extrapos, # FILLETED BIT - ); - } - - $$textref =~ m/\G\s*/gc; - $ld1pos = pos($$textref); - $str1pos = $ld1pos+1; - - unless ($$textref =~ m/\G(\S)/gc) # SHOULD USE LOOKAHEAD - { - _failmsg "No block delimiter found after quotelike $op", - pos $$textref; - pos $$textref = $startpos; - return; - } - pos($$textref) = $ld1pos; # HAVE TO DO THIS BECAUSE LOOKAHEAD BROKEN - my ($ldel1, $rdel1) = ("\Q$1","\Q$1"); - if ($ldel1 =~ /[[(<{]/) - { - $rdel1 =~ tr/[({</])}>/; - defined(_match_bracketed($textref,"",$ldel1,"","",$rdel1)) - || do { pos $$textref = $startpos; return }; - $ld2pos = pos($$textref); - $rd1pos = $ld2pos-1; - } - else - { - $$textref =~ /\G$ldel1[^\\$ldel1]*(\\.[^\\$ldel1]*)*$ldel1/gcs - || do { pos $$textref = $startpos; return }; - $ld2pos = $rd1pos = pos($$textref)-1; - } - - my $second_arg = $op =~ /s|tr|y/ ? 1 : 0; - if ($second_arg) - { - my ($ldel2, $rdel2); - if ($ldel1 =~ /[[(<{]/) - { - unless ($$textref =~ /\G\s*(\S)/gc) # SHOULD USE LOOKAHEAD - { - _failmsg "Missing second block for quotelike $op", - pos $$textref; - pos $$textref = $startpos; - return; - } - $ldel2 = $rdel2 = "\Q$1"; - $rdel2 =~ tr/[({</])}>/; - } - else - { - $ldel2 = $rdel2 = $ldel1; - } - $str2pos = $ld2pos+1; - - if ($ldel2 =~ /[[(<{]/) - { - pos($$textref)--; # OVERCOME BROKEN LOOKAHEAD - defined(_match_bracketed($textref,"",$ldel2,"","",$rdel2)) - || do { pos $$textref = $startpos; return }; - } - else - { - $$textref =~ /[^\\$ldel2]*(\\.[^\\$ldel2]*)*$ldel2/gcs - || do { pos $$textref = $startpos; return }; - } - $rd2pos = pos($$textref)-1; - } - else - { - $ld2pos = $str2pos = $rd2pos = $rd1pos; - } - - $modpos = pos $$textref; - - $$textref =~ m/\G($mods{$op})/gc; - my $endpos = pos $$textref; - - return ( - $startpos, $oppos-$startpos, # PREFIX - $oppos, length($op), # OPERATOR - $ld1pos, 1, # LEFT DEL - $str1pos, $rd1pos-$str1pos, # STR/PAT - $rd1pos, 1, # RIGHT DEL - $ld2pos, $second_arg, # 2ND LDEL (MAYBE) - $str2pos, $rd2pos-$str2pos, # 2ND STR (MAYBE) - $rd2pos, $second_arg, # 2ND RDEL (MAYBE) - $modpos, $endpos-$modpos, # MODIFIERS - $endpos, $textlen-$endpos, # REMAINDER - ); -} - -my $def_func = [ - sub { extract_variable($_[0], '') }, - sub { extract_quotelike($_[0],'') }, - sub { extract_codeblock($_[0],'{}','') }, -]; - -sub extract_multiple (;$$$$) # ($text, $functions_ref, $max_fields, $ignoreunknown) -{ - my $textref = defined($_[0]) ? \$_[0] : \$_; - my $posbug = pos; - my ($lastpos, $firstpos); - my @fields = (); - - #for ($$textref) - { - my @func = defined $_[1] ? @{$_[1]} : @{$def_func}; - my $max = defined $_[2] && $_[2]>0 ? $_[2] : 1_000_000_000; - my $igunk = $_[3]; - - pos $$textref ||= 0; - - unless (wantarray) - { - use Carp; - carp "extract_multiple reset maximal count to 1 in scalar context" - if $^W && defined($_[2]) && $max > 1; - $max = 1 - } - - my $unkpos; - my $func; - my $class; - - my @class; - foreach $func ( @func ) - { - if (ref($func) eq 'HASH') - { - push @class, (keys %$func)[0]; - $func = (values %$func)[0]; - } - else - { - push @class, undef; - } - } - - FIELD: while (pos($$textref) < length($$textref)) - { - my ($field, $rem); - my @bits; - foreach my $i ( 0..$#func ) - { - my $pref; - $func = $func[$i]; - $class = $class[$i]; - $lastpos = pos $$textref; - if (ref($func) eq 'CODE') - { ($field,$rem,$pref) = @bits = $func->($$textref) } - elsif (ref($func) eq 'Text::Balanced::Extractor') - { @bits = $field = $func->extract($$textref) } - elsif( $$textref =~ m/\G$func/gc ) - { @bits = $field = defined($1) - ? $1 - : substr($$textref, $-[0], $+[0] - $-[0]) - } - $pref ||= ""; - if (defined($field) && length($field)) - { - if (!$igunk) { - $unkpos = $lastpos - if length($pref) && !defined($unkpos); - if (defined $unkpos) - { - push @fields, substr($$textref, $unkpos, $lastpos-$unkpos).$pref; - $firstpos = $unkpos unless defined $firstpos; - undef $unkpos; - last FIELD if @fields == $max; - } - } - push @fields, $class - ? bless (\$field, $class) - : $field; - $firstpos = $lastpos unless defined $firstpos; - $lastpos = pos $$textref; - last FIELD if @fields == $max; - next FIELD; - } - } - if ($$textref =~ /\G(.)/gcs) - { - $unkpos = pos($$textref)-1 - unless $igunk || defined $unkpos; - } - } - - if (defined $unkpos) - { - push @fields, substr($$textref, $unkpos); - $firstpos = $unkpos unless defined $firstpos; - $lastpos = length $$textref; - } - last; - } - - pos $$textref = $lastpos; - return @fields if wantarray; - - $firstpos ||= 0; - eval { substr($$textref,$firstpos,$lastpos-$firstpos)=""; - pos $$textref = $firstpos }; - return $fields[0]; -} - -sub gen_extract_tagged # ($opentag, $closetag, $pre, \%options) -{ - my $ldel = $_[0]; - my $rdel = $_[1]; - my $pre = defined $_[2] ? $_[2] : '\s*'; - my %options = defined $_[3] ? %{$_[3]} : (); - my $omode = defined $options{fail} ? $options{fail} : ''; - my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}}) - : defined($options{reject}) ? $options{reject} - : '' - ; - my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}}) - : defined($options{ignore}) ? $options{ignore} - : '' - ; - - if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; } - - my $posbug = pos; - for ($ldel, $pre, $bad, $ignore) { $_ = qr/$_/ if $_ } - pos = $posbug; - - my $closure = sub - { - my $textref = defined $_[0] ? \$_[0] : \$_; - my @match = Text::Balanced::_match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore); - - return _fail(wantarray, $textref) unless @match; - return _succeed wantarray, $textref, - $match[2], $match[3]+$match[5]+$match[7], # MATCH - @match[8..9,0..1,2..7]; # REM, PRE, BITS - }; - - bless $closure, 'Text::Balanced::Extractor'; -} - -package Text::Balanced::Extractor; - -sub extract($$) # ($self, $text) -{ - &{$_[0]}($_[1]); -} - -package Text::Balanced::ErrorMsg; - -use overload '""' => sub { "$_[0]->{error}, detected at offset $_[0]->{pos}" }; - -1; - -__END__ - -=pod - -=head1 NAME - -Text::Balanced - Extract delimited text sequences from strings. - -=head1 SYNOPSIS - - use Text::Balanced qw ( - extract_delimited - extract_bracketed - extract_quotelike - extract_codeblock - extract_variable - extract_tagged - extract_multiple - gen_delimited_pat - gen_extract_tagged - ); - - # Extract the initial substring of $text that is delimited by - # two (unescaped) instances of the first character in $delim. - - ($extracted, $remainder) = extract_delimited($text,$delim); - - - # Extract the initial substring of $text that is bracketed - # with a delimiter(s) specified by $delim (where the string - # in $delim contains one or more of '(){}[]<>'). - - ($extracted, $remainder) = extract_bracketed($text,$delim); - - - # Extract the initial substring of $text that is bounded by - # an XML tag. - - ($extracted, $remainder) = extract_tagged($text); - - - # Extract the initial substring of $text that is bounded by - # a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags - - ($extracted, $remainder) = - extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]}); - - - # Extract the initial substring of $text that represents a - # Perl "quote or quote-like operation" - - ($extracted, $remainder) = extract_quotelike($text); - - - # Extract the initial substring of $text that represents a block - # of Perl code, bracketed by any of character(s) specified by $delim - # (where the string $delim contains one or more of '(){}[]<>'). - - ($extracted, $remainder) = extract_codeblock($text,$delim); - - - # Extract the initial substrings of $text that would be extracted by - # one or more sequential applications of the specified functions - # or regular expressions - - @extracted = extract_multiple($text, - [ \&extract_bracketed, - \&extract_quotelike, - \&some_other_extractor_sub, - qr/[xyz]*/, - 'literal', - ]); - -# Create a string representing an optimized pattern (a la Friedl) -# that matches a substring delimited by any of the specified characters -# (in this case: any type of quote or a slash) - - $patstring = gen_delimited_pat(q{'"`/}); - -# Generate a reference to an anonymous sub that is just like extract_tagged -# but pre-compiled and optimized for a specific pair of tags, and consequently -# much faster (i.e. 3 times faster). It uses qr// for better performance on -# repeated calls, so it only works under Perl 5.005 or later. - - $extract_head = gen_extract_tagged('<HEAD>','</HEAD>'); - - ($extracted, $remainder) = $extract_head->($text); - -=head1 DESCRIPTION - -The various C<extract_...> subroutines may be used to -extract a delimited substring, possibly after skipping a -specified prefix string. By default, that prefix is -optional whitespace (C</\s*/>), but you can change it to whatever -you wish (see below). - -The substring to be extracted must appear at the -current C<pos> location of the string's variable -(or at index zero, if no C<pos> position is defined). -In other words, the C<extract_...> subroutines I<don't> -extract the first occurrence of a substring anywhere -in a string (like an unanchored regex would). Rather, -they extract an occurrence of the substring appearing -immediately at the current matching position in the -string (like a C<\G>-anchored regex would). - -=head2 General behaviour in list contexts - -In a list context, all the subroutines return a list, the first three -elements of which are always: - -=over 4 - -=item [0] - -The extracted string, including the specified delimiters. -If the extraction fails C<undef> is returned. - -=item [1] - -The remainder of the input string (i.e. the characters after the -extracted string). On failure, the entire string is returned. - -=item [2] - -The skipped prefix (i.e. the characters before the extracted string). -On failure, C<undef> is returned. - -=back - -Note that in a list context, the contents of the original input text (the first -argument) are not modified in any way. - -However, if the input text was passed in a variable, that variable's -C<pos> value is updated to point at the first character after the -extracted text. That means that in a list context the various -subroutines can be used much like regular expressions. For example: - - while ( $next = (extract_quotelike($text))[0] ) - { - # process next quote-like (in $next) - } - -=head2 General behaviour in scalar and void contexts - -In a scalar context, the extracted string is returned, having first been -removed from the input text. Thus, the following code also processes -each quote-like operation, but actually removes them from $text: - - while ( $next = extract_quotelike($text) ) - { - # process next quote-like (in $next) - } - -Note that if the input text is a read-only string (i.e. a literal), -no attempt is made to remove the extracted text. - -In a void context the behaviour of the extraction subroutines is -exactly the same as in a scalar context, except (of course) that the -extracted substring is not returned. - -=head2 A note about prefixes - -Prefix patterns are matched without any trailing modifiers (C</gimsox> etc.) -This can bite you if you're expecting a prefix specification like -'.*?(?=<H1>)' to skip everything up to the first <H1> tag. Such a prefix -pattern will only succeed if the <H1> tag is on the current line, since -. normally doesn't match newlines. - -To overcome this limitation, you need to turn on /s matching within -the prefix pattern, using the C<(?s)> directive: '(?s).*?(?=<H1>)' - -=head2 C<extract_delimited> - -The C<extract_delimited> function formalizes the common idiom -of extracting a single-character-delimited substring from the start of -a string. For example, to extract a single-quote delimited string, the -following code is typically used: - - ($remainder = $text) =~ s/\A('(\\.|[^'])*')//s; - $extracted = $1; - -but with C<extract_delimited> it can be simplified to: - - ($extracted,$remainder) = extract_delimited($text, "'"); - -C<extract_delimited> takes up to four scalars (the input text, the -delimiters, a prefix pattern to be skipped, and any escape characters) -and extracts the initial substring of the text that -is appropriately delimited. If the delimiter string has multiple -characters, the first one encountered in the text is taken to delimit -the substring. -The third argument specifies a prefix pattern that is to be skipped -(but must be present!) before the substring is extracted. -The final argument specifies the escape character to be used for each -delimiter. - -All arguments are optional. If the escape characters are not specified, -every delimiter is escaped with a backslash (C<\>). -If the prefix is not specified, the -pattern C<'\s*'> - optional whitespace - is used. If the delimiter set -is also not specified, the set C</["'`]/> is used. If the text to be processed -is not specified either, C<$_> is used. - -In list context, C<extract_delimited> returns a array of three -elements, the extracted substring (I<including the surrounding -delimiters>), the remainder of the text, and the skipped prefix (if -any). If a suitable delimited substring is not found, the first -element of the array is the empty string, the second is the complete -original text, and the prefix returned in the third element is an -empty string. - -In a scalar context, just the extracted substring is returned. In -a void context, the extracted substring (and any prefix) are simply -removed from the beginning of the first argument. - -Examples: - - # Remove a single-quoted substring from the very beginning of $text: - - $substring = extract_delimited($text, "'", ''); - - # Remove a single-quoted Pascalish substring (i.e. one in which - # doubling the quote character escapes it) from the very - # beginning of $text: - - $substring = extract_delimited($text, "'", '', "'"); - - # Extract a single- or double- quoted substring from the - # beginning of $text, optionally after some whitespace - # (note the list context to protect $text from modification): - - ($substring) = extract_delimited $text, q{"'}; - - # Delete the substring delimited by the first '/' in $text: - - $text = join '', (extract_delimited($text,'/','[^/]*')[2,1]; - -Note that this last example is I<not> the same as deleting the first -quote-like pattern. For instance, if C<$text> contained the string: - - "if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }" - -then after the deletion it would contain: - - "if ('.$UNIXCMD/s) { $cmd = $1; }" - -not: - - "if ('./cmd' =~ ms) { $cmd = $1; }" - -See L<"extract_quotelike"> for a (partial) solution to this problem. - -=head2 C<extract_bracketed> - -Like C<"extract_delimited">, the C<extract_bracketed> function takes -up to three optional scalar arguments: a string to extract from, a delimiter -specifier, and a prefix pattern. As before, a missing prefix defaults to -optional whitespace and a missing text defaults to C<$_>. However, a missing -delimiter specifier defaults to C<'{}()[]E<lt>E<gt>'> (see below). - -C<extract_bracketed> extracts a balanced-bracket-delimited -substring (using any one (or more) of the user-specified delimiter -brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it will also -respect quoted unbalanced brackets (see below). - -A "delimiter bracket" is a bracket in list of delimiters passed as -C<extract_bracketed>'s second argument. Delimiter brackets are -specified by giving either the left or right (or both!) versions -of the required bracket(s). Note that the order in which -two or more delimiter brackets are specified is not significant. - -A "balanced-bracket-delimited substring" is a substring bounded by -matched brackets, such that any other (left or right) delimiter -bracket I<within> the substring is also matched by an opposite -(right or left) delimiter bracket I<at the same level of nesting>. Any -type of bracket not in the delimiter list is treated as an ordinary -character. - -In other words, each type of bracket specified as a delimiter must be -balanced and correctly nested within the substring, and any other kind of -("non-delimiter") bracket in the substring is ignored. - -For example, given the string: - - $text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }"; - -then a call to C<extract_bracketed> in a list context: - - @result = extract_bracketed( $text, '{}' ); - -would return: - - ( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" ) - -since both sets of C<'{..}'> brackets are properly nested and evenly balanced. -(In a scalar context just the first element of the array would be returned. In -a void context, C<$text> would be replaced by an empty string.) - -Likewise the call in: - - @result = extract_bracketed( $text, '{[' ); - -would return the same result, since all sets of both types of specified -delimiter brackets are correctly nested and balanced. - -However, the call in: - - @result = extract_bracketed( $text, '{([<' ); - -would fail, returning: - - ( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }" ); - -because the embedded pairs of C<'(..)'>s and C<'[..]'>s are "cross-nested" and -the embedded C<'E<gt>'> is unbalanced. (In a scalar context, this call would -return an empty string. In a void context, C<$text> would be unchanged.) - -Note that the embedded single-quotes in the string don't help in this -case, since they have not been specified as acceptable delimiters and are -therefore treated as non-delimiter characters (and ignored). - -However, if a particular species of quote character is included in the -delimiter specification, then that type of quote will be correctly handled. -for example, if C<$text> is: - - $text = '<A HREF=">>>>">link</A>'; - -then - - @result = extract_bracketed( $text, '<">' ); - -returns: - - ( '<A HREF=">>>>">', 'link</A>', "" ) - -as expected. Without the specification of C<"> as an embedded quoter: - - @result = extract_bracketed( $text, '<>' ); - -the result would be: - - ( '<A HREF=">', '>>>">link</A>', "" ) - -In addition to the quote delimiters C<'>, C<">, and C<`>, full Perl quote-like -quoting (i.e. q{string}, qq{string}, etc) can be specified by including the -letter 'q' as a delimiter. Hence: - - @result = extract_bracketed( $text, '<q>' ); - -would correctly match something like this: - - $text = '<leftop: conj /and/ conj>'; - -See also: C<"extract_quotelike"> and C<"extract_codeblock">. - -=head2 C<extract_variable> - -C<extract_variable> extracts any valid Perl variable or -variable-involved expression, including scalars, arrays, hashes, array -accesses, hash look-ups, method calls through objects, subroutine calls -through subroutine references, etc. - -The subroutine takes up to two optional arguments: - -=over 4 - -=item 1. - -A string to be processed (C<$_> if the string is omitted or C<undef>) - -=item 2. - -A string specifying a pattern to be matched as a prefix (which is to be -skipped). If omitted, optional whitespace is skipped. - -=back - -On success in a list context, an array of 3 elements is returned. The -elements are: - -=over 4 - -=item [0] - -the extracted variable, or variablish expression - -=item [1] - -the remainder of the input text, - -=item [2] - -the prefix substring (if any), - -=back - -On failure, all of these values (except the remaining text) are C<undef>. - -In a scalar context, C<extract_variable> returns just the complete -substring that matched a variablish expression. C<undef> is returned on -failure. In addition, the original input text has the returned substring -(and any prefix) removed from it. - -In a void context, the input text just has the matched substring (and -any specified prefix) removed. - - -=head2 C<extract_tagged> - -C<extract_tagged> extracts and segments text between (balanced) -specified tags. - -The subroutine takes up to five optional arguments: - -=over 4 - -=item 1. - -A string to be processed (C<$_> if the string is omitted or C<undef>) - -=item 2. - -A string specifying a pattern to be matched as the opening tag. -If the pattern string is omitted (or C<undef>) then a pattern -that matches any standard XML tag is used. - -=item 3. - -A string specifying a pattern to be matched at the closing tag. -If the pattern string is omitted (or C<undef>) then the closing -tag is constructed by inserting a C</> after any leading bracket -characters in the actual opening tag that was matched (I<not> the pattern -that matched the tag). For example, if the opening tag pattern -is specified as C<'{{\w+}}'> and actually matched the opening tag -C<"{{DATA}}">, then the constructed closing tag would be C<"{{/DATA}}">. - -=item 4. - -A string specifying a pattern to be matched as a prefix (which is to be -skipped). If omitted, optional whitespace is skipped. - -=item 5. - -A hash reference containing various parsing options (see below) - -=back - -The various options that can be specified are: - -=over 4 - -=item C<reject =E<gt> $listref> - -The list reference contains one or more strings specifying patterns -that must I<not> appear within the tagged text. - -For example, to extract -an HTML link (which should not contain nested links) use: - - extract_tagged($text, '<A>', '</A>', undef, {reject => ['<A>']} ); - -=item C<ignore =E<gt> $listref> - -The list reference contains one or more strings specifying patterns -that are I<not> be be treated as nested tags within the tagged text -(even if they would match the start tag pattern). - -For example, to extract an arbitrary XML tag, but ignore "empty" elements: - - extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} ); - -(also see L<"gen_delimited_pat"> below). - -=item C<fail =E<gt> $str> - -The C<fail> option indicates the action to be taken if a matching end -tag is not encountered (i.e. before the end of the string or some -C<reject> pattern matches). By default, a failure to match a closing -tag causes C<extract_tagged> to immediately fail. - -However, if the string value associated with <reject> is "MAX", then -C<extract_tagged> returns the complete text up to the point of failure. -If the string is "PARA", C<extract_tagged> returns only the first paragraph -after the tag (up to the first line that is either empty or contains -only whitespace characters). -If the string is "", the the default behaviour (i.e. failure) is reinstated. - -For example, suppose the start tag "/para" introduces a paragraph, which then -continues until the next "/endpara" tag or until another "/para" tag is -encountered: - - $text = "/para line 1\n\nline 3\n/para line 4"; - - extract_tagged($text, '/para', '/endpara', undef, - {reject => '/para', fail => MAX ); - - # EXTRACTED: "/para line 1\n\nline 3\n" - -Suppose instead, that if no matching "/endpara" tag is found, the "/para" -tag refers only to the immediately following paragraph: - - $text = "/para line 1\n\nline 3\n/para line 4"; - - extract_tagged($text, '/para', '/endpara', undef, - {reject => '/para', fail => MAX ); - - # EXTRACTED: "/para line 1\n" - -Note that the specified C<fail> behaviour applies to nested tags as well. - -=back - -On success in a list context, an array of 6 elements is returned. The elements are: - -=over 4 - -=item [0] - -the extracted tagged substring (including the outermost tags), - -=item [1] - -the remainder of the input text, - -=item [2] - -the prefix substring (if any), - -=item [3] - -the opening tag - -=item [4] - -the text between the opening and closing tags - -=item [5] - -the closing tag (or "" if no closing tag was found) - -=back - -On failure, all of these values (except the remaining text) are C<undef>. - -In a scalar context, C<extract_tagged> returns just the complete -substring that matched a tagged text (including the start and end -tags). C<undef> is returned on failure. In addition, the original input -text has the returned substring (and any prefix) removed from it. - -In a void context, the input text just has the matched substring (and -any specified prefix) removed. - -=head2 C<gen_extract_tagged> - -(Note: This subroutine is only available under Perl5.005) - -C<gen_extract_tagged> generates a new anonymous subroutine which -extracts text between (balanced) specified tags. In other words, -it generates a function identical in function to C<extract_tagged>. - -The difference between C<extract_tagged> and the anonymous -subroutines generated by -C<gen_extract_tagged>, is that those generated subroutines: - -=over 4 - -=item * - -do not have to reparse tag specification or parsing options every time -they are called (whereas C<extract_tagged> has to effectively rebuild -its tag parser on every call); - -=item * - -make use of the new qr// construct to pre-compile the regexes they use -(whereas C<extract_tagged> uses standard string variable interpolation -to create tag-matching patterns). - -=back - -The subroutine takes up to four optional arguments (the same set as -C<extract_tagged> except for the string to be processed). It returns -a reference to a subroutine which in turn takes a single argument (the text to -be extracted from). - -In other words, the implementation of C<extract_tagged> is exactly -equivalent to: - - sub extract_tagged - { - my $text = shift; - $extractor = gen_extract_tagged(@_); - return $extractor->($text); - } - -(although C<extract_tagged> is not currently implemented that way, in order -to preserve pre-5.005 compatibility). - -Using C<gen_extract_tagged> to create extraction functions for specific tags -is a good idea if those functions are going to be called more than once, since -their performance is typically twice as good as the more general-purpose -C<extract_tagged>. - - -=head2 C<extract_quotelike> - -C<extract_quotelike> attempts to recognize, extract, and segment any -one of the various Perl quotes and quotelike operators (see -L<perlop(3)>) Nested backslashed delimiters, embedded balanced bracket -delimiters (for the quotelike operators), and trailing modifiers are -all caught. For example, in: - - extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #' - - extract_quotelike ' "You said, \"Use sed\"." ' - - extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; ' - - extract_quotelike ' tr/\\\/\\\\/\\\//ds; ' - -the full Perl quotelike operations are all extracted correctly. - -Note too that, when using the /x modifier on a regex, any comment -containing the current pattern delimiter will cause the regex to be -immediately terminated. In other words: - - 'm / - (?i) # CASE INSENSITIVE - [a-z_] # LEADING ALPHABETIC/UNDERSCORE - [a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS - /x' - -will be extracted as if it were: - - 'm / - (?i) # CASE INSENSITIVE - [a-z_] # LEADING ALPHABETIC/' - -This behaviour is identical to that of the actual compiler. - -C<extract_quotelike> takes two arguments: the text to be processed and -a prefix to be matched at the very beginning of the text. If no prefix -is specified, optional whitespace is the default. If no text is given, -C<$_> is used. - -In a list context, an array of 11 elements is returned. The elements are: - -=over 4 - -=item [0] - -the extracted quotelike substring (including trailing modifiers), - -=item [1] - -the remainder of the input text, - -=item [2] - -the prefix substring (if any), - -=item [3] - -the name of the quotelike operator (if any), - -=item [4] - -the left delimiter of the first block of the operation, - -=item [5] - -the text of the first block of the operation -(that is, the contents of -a quote, the regex of a match or substitution or the target list of a -translation), - -=item [6] - -the right delimiter of the first block of the operation, - -=item [7] - -the left delimiter of the second block of the operation -(that is, if it is a C<s>, C<tr>, or C<y>), - -=item [8] - -the text of the second block of the operation -(that is, the replacement of a substitution or the translation list -of a translation), - -=item [9] - -the right delimiter of the second block of the operation (if any), - -=item [10] - -the trailing modifiers on the operation (if any). - -=back - -For each of the fields marked "(if any)" the default value on success is -an empty string. -On failure, all of these values (except the remaining text) are C<undef>. - -In a scalar context, C<extract_quotelike> returns just the complete substring -that matched a quotelike operation (or C<undef> on failure). In a scalar or -void context, the input text has the same substring (and any specified -prefix) removed. - -Examples: - - # Remove the first quotelike literal that appears in text - - $quotelike = extract_quotelike($text,'.*?'); - - # Replace one or more leading whitespace-separated quotelike - # literals in $_ with "<QLL>" - - do { $_ = join '<QLL>', (extract_quotelike)[2,1] } until $@; - - - # Isolate the search pattern in a quotelike operation from $text - - ($op,$pat) = (extract_quotelike $text)[3,5]; - if ($op =~ /[ms]/) - { - print "search pattern: $pat\n"; - } - else - { - print "$op is not a pattern matching operation\n"; - } - -=head2 C<extract_quotelike> and "here documents" - -C<extract_quotelike> can successfully extract "here documents" from an input -string, but with an important caveat in list contexts. - -Unlike other types of quote-like literals, a here document is rarely -a contiguous substring. For example, a typical piece of code using -here document might look like this: - - <<'EOMSG' || die; - This is the message. - EOMSG - exit; - -Given this as an input string in a scalar context, C<extract_quotelike> -would correctly return the string "<<'EOMSG'\nThis is the message.\nEOMSG", -leaving the string " || die;\nexit;" in the original variable. In other words, -the two separate pieces of the here document are successfully extracted and -concatenated. - -In a list context, C<extract_quotelike> would return the list - -=over 4 - -=item [0] - -"<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted here document, -including fore and aft delimiters), - -=item [1] - -" || die;\nexit;" (i.e. the remainder of the input text, concatenated), - -=item [2] - -"" (i.e. the prefix substring -- trivial in this case), - -=item [3] - -"<<" (i.e. the "name" of the quotelike operator) - -=item [4] - -"'EOMSG'" (i.e. the left delimiter of the here document, including any quotes), - -=item [5] - -"This is the message.\n" (i.e. the text of the here document), - -=item [6] - -"EOMSG" (i.e. the right delimiter of the here document), - -=item [7..10] - -"" (a here document has no second left delimiter, second text, second right -delimiter, or trailing modifiers). - -=back - -However, the matching position of the input variable would be set to -"exit;" (i.e. I<after> the closing delimiter of the here document), -which would cause the earlier " || die;\nexit;" to be skipped in any -sequence of code fragment extractions. - -To avoid this problem, when it encounters a here document whilst -extracting from a modifiable string, C<extract_quotelike> silently -rearranges the string to an equivalent piece of Perl: - - <<'EOMSG' - This is the message. - EOMSG - || die; - exit; - -in which the here document I<is> contiguous. It still leaves the -matching position after the here document, but now the rest of the line -on which the here document starts is not skipped. - -To prevent <extract_quotelike> from mucking about with the input in this way -(this is the only case where a list-context C<extract_quotelike> does so), -you can pass the input variable as an interpolated literal: - - $quotelike = extract_quotelike("$var"); - -=head2 C<extract_codeblock> - -C<extract_codeblock> attempts to recognize and extract a balanced -bracket delimited substring that may contain unbalanced brackets -inside Perl quotes or quotelike operations. That is, C<extract_codeblock> -is like a combination of C<"extract_bracketed"> and -C<"extract_quotelike">. - -C<extract_codeblock> takes the same initial three parameters as C<extract_bracketed>: -a text to process, a set of delimiter brackets to look for, and a prefix to -match first. It also takes an optional fourth parameter, which allows the -outermost delimiter brackets to be specified separately (see below). - -Omitting the first argument (input text) means process C<$_> instead. -Omitting the second argument (delimiter brackets) indicates that only C<'{'> is to be used. -Omitting the third argument (prefix argument) implies optional whitespace at the start. -Omitting the fourth argument (outermost delimiter brackets) indicates that the -value of the second argument is to be used for the outermost delimiters. - -Once the prefix an dthe outermost opening delimiter bracket have been -recognized, code blocks are extracted by stepping through the input text and -trying the following alternatives in sequence: - -=over 4 - -=item 1. - -Try and match a closing delimiter bracket. If the bracket was the same -species as the last opening bracket, return the substring to that -point. If the bracket was mismatched, return an error. - -=item 2. - -Try to match a quote or quotelike operator. If found, call -C<extract_quotelike> to eat it. If C<extract_quotelike> fails, return -the error it returned. Otherwise go back to step 1. - -=item 3. - -Try to match an opening delimiter bracket. If found, call -C<extract_codeblock> recursively to eat the embedded block. If the -recursive call fails, return an error. Otherwise, go back to step 1. - -=item 4. - -Unconditionally match a bareword or any other single character, and -then go back to step 1. - -=back - -Examples: - - # Find a while loop in the text - - if ($text =~ s/.*?while\s*\{/{/) - { - $loop = "while " . extract_codeblock($text); - } - - # Remove the first round-bracketed list (which may include - # round- or curly-bracketed code blocks or quotelike operators) - - extract_codeblock $text, "(){}", '[^(]*'; - - -The ability to specify a different outermost delimiter bracket is useful -in some circumstances. For example, in the Parse::RecDescent module, -parser actions which are to be performed only on a successful parse -are specified using a C<E<lt>defer:...E<gt>> directive. For example: - - sentence: subject verb object - <defer: {$::theVerb = $item{verb}} > - -Parse::RecDescent uses C<extract_codeblock($text, '{}E<lt>E<gt>')> to extract the code -within the C<E<lt>defer:...E<gt>> directive, but there's a problem. - -A deferred action like this: - - <defer: {if ($count>10) {$count--}} > - -will be incorrectly parsed as: - - <defer: {if ($count> - -because the "less than" operator is interpreted as a closing delimiter. - -But, by extracting the directive using -S<C<extract_codeblock($text, '{}', undef, 'E<lt>E<gt>')>> -the '>' character is only treated as a delimited at the outermost -level of the code block, so the directive is parsed correctly. - -=head2 C<extract_multiple> - -The C<extract_multiple> subroutine takes a string to be processed and a -list of extractors (subroutines or regular expressions) to apply to that string. - -In an array context C<extract_multiple> returns an array of substrings -of the original string, as extracted by the specified extractors. -In a scalar context, C<extract_multiple> returns the first -substring successfully extracted from the original string. In both -scalar and void contexts the original string has the first successfully -extracted substring removed from it. In all contexts -C<extract_multiple> starts at the current C<pos> of the string, and -sets that C<pos> appropriately after it matches. - -Hence, the aim of of a call to C<extract_multiple> in a list context -is to split the processed string into as many non-overlapping fields as -possible, by repeatedly applying each of the specified extractors -to the remainder of the string. Thus C<extract_multiple> is -a generalized form of Perl's C<split> subroutine. - -The subroutine takes up to four optional arguments: - -=over 4 - -=item 1. - -A string to be processed (C<$_> if the string is omitted or C<undef>) - -=item 2. - -A reference to a list of subroutine references and/or qr// objects and/or -literal strings and/or hash references, specifying the extractors -to be used to split the string. If this argument is omitted (or -C<undef>) the list: - - [ - sub { extract_variable($_[0], '') }, - sub { extract_quotelike($_[0],'') }, - sub { extract_codeblock($_[0],'{}','') }, - ] - -is used. - -=item 3. - -An number specifying the maximum number of fields to return. If this -argument is omitted (or C<undef>), split continues as long as possible. - -If the third argument is I<N>, then extraction continues until I<N> fields -have been successfully extracted, or until the string has been completely -processed. - -Note that in scalar and void contexts the value of this argument is -automatically reset to 1 (under C<-w>, a warning is issued if the argument -has to be reset). - -=item 4. - -A value indicating whether unmatched substrings (see below) within the -text should be skipped or returned as fields. If the value is true, -such substrings are skipped. Otherwise, they are returned. - -=back - -The extraction process works by applying each extractor in -sequence to the text string. - -If the extractor is a subroutine it is called in a list context and is -expected to return a list of a single element, namely the extracted -text. It may optionally also return two further arguments: a string -representing the text left after extraction (like $' for a pattern -match), and a string representing any prefix skipped before the -extraction (like $` in a pattern match). Note that this is designed -to facilitate the use of other Text::Balanced subroutines with -C<extract_multiple>. Note too that the value returned by an extractor -subroutine need not bear any relationship to the corresponding substring -of the original text (see examples below). - -If the extractor is a precompiled regular expression or a string, -it is matched against the text in a scalar context with a leading -'\G' and the gc modifiers enabled. The extracted value is either -$1 if that variable is defined after the match, or else the -complete match (i.e. $&). - -If the extractor is a hash reference, it must contain exactly one element. -The value of that element is one of the -above extractor types (subroutine reference, regular expression, or string). -The key of that element is the name of a class into which the successful -return value of the extractor will be blessed. - -If an extractor returns a defined value, that value is immediately -treated as the next extracted field and pushed onto the list of fields. -If the extractor was specified in a hash reference, the field is also -blessed into the appropriate class, - -If the extractor fails to match (in the case of a regex extractor), or returns an empty list or an undefined value (in the case of a subroutine extractor), it is -assumed to have failed to extract. -If none of the extractor subroutines succeeds, then one -character is extracted from the start of the text and the extraction -subroutines reapplied. Characters which are thus removed are accumulated and -eventually become the next field (unless the fourth argument is true, in which -case they are discarded). - -For example, the following extracts substrings that are valid Perl variables: - - @fields = extract_multiple($text, - [ sub { extract_variable($_[0]) } ], - undef, 1); - -This example separates a text into fields which are quote delimited, -curly bracketed, and anything else. The delimited and bracketed -parts are also blessed to identify them (the "anything else" is unblessed): - - @fields = extract_multiple($text, - [ - { Delim => sub { extract_delimited($_[0],q{'"}) } }, - { Brack => sub { extract_bracketed($_[0],'{}') } }, - ]); - -This call extracts the next single substring that is a valid Perl quotelike -operator (and removes it from $text): - - $quotelike = extract_multiple($text, - [ - sub { extract_quotelike($_[0]) }, - ], undef, 1); - -Finally, here is yet another way to do comma-separated value parsing: - - @fields = extract_multiple($csv_text, - [ - sub { extract_delimited($_[0],q{'"}) }, - qr/([^,]+)(.*)/, - ], - undef,1); - -The list in the second argument means: -I<"Try and extract a ' or " delimited string, otherwise extract anything up to a comma...">. -The undef third argument means: -I<"...as many times as possible...">, -and the true value in the fourth argument means -I<"...discarding anything else that appears (i.e. the commas)">. - -If you wanted the commas preserved as separate fields (i.e. like split -does if your split pattern has capturing parentheses), you would -just make the last parameter undefined (or remove it). - -=head2 C<gen_delimited_pat> - -The C<gen_delimited_pat> subroutine takes a single (string) argument and - > builds a Friedl-style optimized regex that matches a string delimited -by any one of the characters in the single argument. For example: - - gen_delimited_pat(q{'"}) - -returns the regex: - - (?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\') - -Note that the specified delimiters are automatically quotemeta'd. - -A typical use of C<gen_delimited_pat> would be to build special purpose tags -for C<extract_tagged>. For example, to properly ignore "empty" XML elements -(which might contain quoted strings): - - my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>'; - - extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} ); - -C<gen_delimited_pat> may also be called with an optional second argument, -which specifies the "escape" character(s) to be used for each delimiter. -For example to match a Pascal-style string (where ' is the delimiter -and '' is a literal ' within the string): - - gen_delimited_pat(q{'},q{'}); - -Different escape characters can be specified for different delimiters. -For example, to specify that '/' is the escape for single quotes -and '%' is the escape for double quotes: - - gen_delimited_pat(q{'"},q{/%}); - -If more delimiters than escape chars are specified, the last escape char -is used for the remaining delimiters. -If no escape char is specified for a given specified delimiter, '\' is used. - -=head2 C<delimited_pat> - -Note that C<gen_delimited_pat> was previously called C<delimited_pat>. -That name may still be used, but is now deprecated. - - -=head1 DIAGNOSTICS - -In a list context, all the functions return C<(undef,$original_text)> -on failure. In a scalar context, failure is indicated by returning C<undef> -(in this case the input text is not modified in any way). - -In addition, on failure in I<any> context, the C<$@> variable is set. -Accessing C<$@-E<gt>{error}> returns one of the error diagnostics listed -below. -Accessing C<$@-E<gt>{pos}> returns the offset into the original string at -which the error was detected (although not necessarily where it occurred!) -Printing C<$@> directly produces the error message, with the offset appended. -On success, the C<$@> variable is guaranteed to be C<undef>. - -The available diagnostics are: - -=over 4 - -=item C<Did not find a suitable bracket: "%s"> - -The delimiter provided to C<extract_bracketed> was not one of -C<'()[]E<lt>E<gt>{}'>. - -=item C<Did not find prefix: /%s/> - -A non-optional prefix was specified but wasn't found at the start of the text. - -=item C<Did not find opening bracket after prefix: "%s"> - -C<extract_bracketed> or C<extract_codeblock> was expecting a -particular kind of bracket at the start of the text, and didn't find it. - -=item C<No quotelike operator found after prefix: "%s"> - -C<extract_quotelike> didn't find one of the quotelike operators C<q>, -C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y> at the start of the substring -it was extracting. - -=item C<Unmatched closing bracket: "%c"> - -C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> encountered -a closing bracket where none was expected. - -=item C<Unmatched opening bracket(s): "%s"> - -C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> ran -out of characters in the text before closing one or more levels of nested -brackets. - -=item C<Unmatched embedded quote (%s)> - -C<extract_bracketed> attempted to match an embedded quoted substring, but -failed to find a closing quote to match it. - -=item C<Did not find closing delimiter to match '%s'> - -C<extract_quotelike> was unable to find a closing delimiter to match the -one that opened the quote-like operation. - -=item C<Mismatched closing bracket: expected "%c" but found "%s"> - -C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> found -a valid bracket delimiter, but it was the wrong species. This usually -indicates a nesting error, but may indicate incorrect quoting or escaping. - -=item C<No block delimiter found after quotelike "%s"> - -C<extract_quotelike> or C<extract_codeblock> found one of the -quotelike operators C<q>, C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y> -without a suitable block after it. - -=item C<Did not find leading dereferencer> - -C<extract_variable> was expecting one of '$', '@', or '%' at the start of -a variable, but didn't find any of them. - -=item C<Bad identifier after dereferencer> - -C<extract_variable> found a '$', '@', or '%' indicating a variable, but that -character was not followed by a legal Perl identifier. - -=item C<Did not find expected opening bracket at %s> - -C<extract_codeblock> failed to find any of the outermost opening brackets -that were specified. - -=item C<Improperly nested codeblock at %s> - -A nested code block was found that started with a delimiter that was specified -as being only to be used as an outermost bracket. - -=item C<Missing second block for quotelike "%s"> - -C<extract_codeblock> or C<extract_quotelike> found one of the -quotelike operators C<s>, C<tr> or C<y> followed by only one block. - -=item C<No match found for opening bracket> - -C<extract_codeblock> failed to find a closing bracket to match the outermost -opening bracket. - -=item C<Did not find opening tag: /%s/> - -C<extract_tagged> did not find a suitable opening tag (after any specified -prefix was removed). - -=item C<Unable to construct closing tag to match: /%s/> - -C<extract_tagged> matched the specified opening tag and tried to -modify the matched text to produce a matching closing tag (because -none was specified). It failed to generate the closing tag, almost -certainly because the opening tag did not start with a -bracket of some kind. - -=item C<Found invalid nested tag: %s> - -C<extract_tagged> found a nested tag that appeared in the "reject" list -(and the failure mode was not "MAX" or "PARA"). - -=item C<Found unbalanced nested tag: %s> - -C<extract_tagged> found a nested opening tag that was not matched by a -corresponding nested closing tag (and the failure mode was not "MAX" or "PARA"). - -=item C<Did not find closing tag> - -C<extract_tagged> reached the end of the text without finding a closing tag -to match the original opening tag (and the failure mode was not -"MAX" or "PARA"). - -=back - -=head1 AUTHOR - -Damian Conway (damian@conway.org) - -=head1 BUGS AND IRRITATIONS - -There are undoubtedly serious bugs lurking somewhere in this code, if -only because parts of it give the impression of understanding a great deal -more about Perl than they really do. - -Bug reports and other feedback are most welcome. - -=head1 COPYRIGHT - -Copyright 1997 - 2001 Damian Conway. All Rights Reserved. - -Some (minor) parts copyright 2009 Adam Kennedy. - -This module is free software. It may be used, redistributed -and/or modified under the same terms as Perl itself. - -=cut diff --git a/Master/tlpkg/tlperl/lib/Text/Diff.pm b/Master/tlpkg/tlperl/lib/Text/Diff.pm deleted file mode 100755 index 8decbbdb407..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Diff.pm +++ /dev/null @@ -1,713 +0,0 @@ -package Text::Diff; - -use 5.00503; -use strict; -use Carp; -use Exporter (); -use Algorithm::Diff (); -use vars qw{$VERSION @ISA @EXPORT}; -BEGIN { - $VERSION = '1.37'; - @ISA = 'Exporter'; - @EXPORT = 'diff'; -}; - -## Hunks are made of ops. An op is the starting index for each -## sequence and the opcode: -use constant A => 0; # Array index before match/discard -use constant B => 1; -use constant OPCODE => 2; # "-", " ", "+" -use constant FLAG => 3; # What to display if not OPCODE "!" - -my %internal_styles = ( - Unified => undef, - Context => undef, - OldStyle => undef, - Table => undef, ## "internal", but in another module -); - -sub diff { - my @seqs = ( shift, shift ); - my $options = shift || {}; - - for my $i ( 0 .. 1 ) { - my $seq = $seqs[$i]; - my $type = ref $seq; - - while ( $type eq "CODE" ) { - $seqs[$i] = $seq = $seq->( $options ); - $type = ref $seq; - } - - my $AorB = !$i ? "A" : "B"; - - if ( $type eq "ARRAY" ) { - ## This is most efficient :) - $options->{"OFFSET_$AorB"} = 0 - unless defined $options->{"OFFSET_$AorB"}; - } - elsif ( $type eq "SCALAR" ) { - $seqs[$i] = [split( /^/m, $$seq )]; - $options->{"OFFSET_$AorB"} = 1 - unless defined $options->{"OFFSET_$AorB"}; - } - elsif ( ! $type ) { - $options->{"OFFSET_$AorB"} = 1 - unless defined $options->{"OFFSET_$AorB"}; - $options->{"FILENAME_$AorB"} = $seq - unless defined $options->{"FILENAME_$AorB"}; - $options->{"MTIME_$AorB"} = (stat($seq))[9] - unless defined $options->{"MTIME_$AorB"}; - - local $/ = "\n"; - open F, "<$seq" or carp "$!: $seq"; - $seqs[$i] = [<F>]; - close F; - - } - elsif ( $type eq "GLOB" || UNIVERSAL::isa( $seq, "IO::Handle" ) ) { - $options->{"OFFSET_$AorB"} = 1 - unless defined $options->{"OFFSET_$AorB"}; - local $/ = "\n"; - $seqs[$i] = [<$seq>]; - } - else { - confess "Can't handle input of type ", ref; - } - } - - ## Config vars - my $output; - my $output_handler = $options->{OUTPUT}; - my $type = ref $output_handler ; - if ( ! defined $output_handler ) { - $output = ""; - $output_handler = sub { $output .= shift }; - } - elsif ( $type eq "CODE" ) { - ## No problems, mate. - } - elsif ( $type eq "SCALAR" ) { - my $out_ref = $output_handler; - $output_handler = sub { $$out_ref .= shift }; - } - elsif ( $type eq "ARRAY" ) { - my $out_ref = $output_handler; - $output_handler = sub { push @$out_ref, shift }; - } - elsif ( $type eq "GLOB" || UNIVERSAL::isa $output_handler, "IO::Handle" ) { - my $output_handle = $output_handler; - $output_handler = sub { print $output_handle shift }; - } - else { - croak "Unrecognized output type: $type"; - } - - my $style = $options->{STYLE}; - $style = "Unified" unless defined $options->{STYLE}; - $style = "Text::Diff::$style" if exists $internal_styles{$style}; - - if ( ! $style->can( "hunk" ) ) { - eval "require $style; 1" or die $@; - } - - $style = $style->new - if ! ref $style && $style->can( "new" ); - - my $ctx_lines = $options->{CONTEXT}; - $ctx_lines = 3 unless defined $ctx_lines; - $ctx_lines = 0 if $style->isa( "Text::Diff::OldStyle" ); - - my @keygen_args = $options->{KEYGEN_ARGS} - ? @{$options->{KEYGEN_ARGS}} - : (); - - ## State vars - my $diffs = 0; ## Number of discards this hunk - my $ctx = 0; ## Number of " " (ctx_lines) ops pushed after last diff. - my @ops; ## ops (" ", +, -) in this hunk - my $hunks = 0; ## Number of hunks - - my $emit_ops = sub { - $output_handler->( $style->file_header( @seqs, $options ) ) - unless $hunks++; - $output_handler->( $style->hunk_header( @seqs, @_, $options ) ); - $output_handler->( $style->hunk ( @seqs, @_, $options ) ); - $output_handler->( $style->hunk_footer( @seqs, @_, $options ) ); - }; - - ## We keep 2*ctx_lines so that if a diff occurs - ## at 2*ctx_lines we continue to grow the hunk instead - ## of emitting diffs and context as we go. We - ## need to know the total length of both of the two - ## subsequences so the line count can be printed in the - ## header. - my $dis_a = sub {push @ops, [@_[0,1],"-"]; ++$diffs ; $ctx = 0 }; - my $dis_b = sub {push @ops, [@_[0,1],"+"]; ++$diffs ; $ctx = 0 }; - - Algorithm::Diff::traverse_sequences( - @seqs, - { - MATCH => sub { - push @ops, [@_[0,1]," "]; - - if ( $diffs && ++$ctx > $ctx_lines * 2 ) { - $emit_ops->( [ splice @ops, 0, $#ops - $ctx_lines ] ); - $ctx = $diffs = 0; - } - - ## throw away context lines that aren't needed any more - shift @ops if ! $diffs && @ops > $ctx_lines; - }, - DISCARD_A => $dis_a, - DISCARD_B => $dis_b, - }, - $options->{KEYGEN}, # pass in user arguments for key gen function - @keygen_args, - ); - - if ( $diffs ) { - $#ops -= $ctx - $ctx_lines if $ctx > $ctx_lines; - $emit_ops->( \@ops ); - } - - $output_handler->( $style->file_footer( @seqs, $options ) ) if $hunks; - - return defined $output ? $output : $hunks; -} - -sub _header { - my ( $h ) = @_; - my ( $p1, $fn1, $t1, $p2, $fn2, $t2 ) = @{$h}{ - "FILENAME_PREFIX_A", - "FILENAME_A", - "MTIME_A", - "FILENAME_PREFIX_B", - "FILENAME_B", - "MTIME_B" - }; - - ## remember to change Text::Diff::Table if this logic is tweaked. - return "" unless defined $fn1 && defined $fn2; - - return join( "", - $p1, " ", $fn1, defined $t1 ? "\t" . localtime $t1 : (), "\n", - $p2, " ", $fn2, defined $t2 ? "\t" . localtime $t2 : (), "\n", - ); -} - -## _range encapsulates the building of, well, ranges. Turns out there are -## a few nuances. -sub _range { - my ( $ops, $a_or_b, $format ) = @_; - - my $start = $ops->[ 0]->[$a_or_b]; - my $after = $ops->[-1]->[$a_or_b]; - - ## The sequence indexes in the lines are from *before* the OPCODE is - ## executed, so we bump the last index up unless the OP indicates - ## it didn't change. - ++$after - unless $ops->[-1]->[OPCODE] eq ( $a_or_b == A ? "+" : "-" ); - - ## convert from 0..n index to 1..(n+1) line number. The unless modifier - ## handles diffs with no context, where only one file is affected. In this - ## case $start == $after indicates an empty range, and the $start must - ## not be incremented. - my $empty_range = $start == $after; - ++$start unless $empty_range; - - return - $start == $after - ? $format eq "unified" && $empty_range - ? "$start,0" - : $start - : $format eq "unified" - ? "$start,".($after-$start+1) - : "$start,$after"; -} - -sub _op_to_line { - my ( $seqs, $op, $a_or_b, $op_prefixes ) = @_; - - my $opcode = $op->[OPCODE]; - return () unless defined $op_prefixes->{$opcode}; - - my $op_sym = defined $op->[FLAG] ? $op->[FLAG] : $opcode; - $op_sym = $op_prefixes->{$op_sym}; - return () unless defined $op_sym; - - $a_or_b = $op->[OPCODE] ne "+" ? 0 : 1 unless defined $a_or_b; - return ( $op_sym, $seqs->[$a_or_b][$op->[$a_or_b]] ); -} - -SCOPE: { - package Text::Diff::Base; - - sub new { - my $proto = shift; - return bless { @_ }, ref $proto || $proto; - } - - sub file_header { return "" } - - sub hunk_header { return "" } - - sub hunk { return "" } - - sub hunk_footer { return "" } - - sub file_footer { return "" } -} - -@Text::Diff::Unified::ISA = qw( Text::Diff::Base ); - -sub Text::Diff::Unified::file_header { - shift; ## No instance data - my $options = pop ; - - _header( - { FILENAME_PREFIX_A => "---", FILENAME_PREFIX_B => "+++", %$options } - ); -} - -sub Text::Diff::Unified::hunk_header { - shift; ## No instance data - pop; ## Ignore options - my $ops = pop; - - return join( "", - "@@ -", - _range( $ops, A, "unified" ), - " +", - _range( $ops, B, "unified" ), - " @@\n", - ); -} - -sub Text::Diff::Unified::hunk { - shift; ## No instance data - pop; ## Ignore options - my $ops = pop; - - my $prefixes = { "+" => "+", " " => " ", "-" => "-" }; - - return join "", map _op_to_line( \@_, $_, undef, $prefixes ), @$ops -} - -@Text::Diff::Context::ISA = qw( Text::Diff::Base ); - -sub Text::Diff::Context::file_header { - _header { FILENAME_PREFIX_A=>"***", FILENAME_PREFIX_B=>"---", %{$_[-1]} }; -} - -sub Text::Diff::Context::hunk_header { - return "***************\n"; -} - -sub Text::Diff::Context::hunk { - shift; ## No instance data - pop; ## Ignore options - my $ops = pop; - ## Leave the sequences in @_[0,1] - - my $a_range = _range( $ops, A, "" ); - my $b_range = _range( $ops, B, "" ); - - ## Sigh. Gotta make sure that differences that aren't adds/deletions - ## get prefixed with "!", and that the old opcodes are removed. - my $after; - for ( my $start = 0; $start <= $#$ops ; $start = $after ) { - ## Scan until next difference - $after = $start + 1; - my $opcode = $ops->[$start]->[OPCODE]; - next if $opcode eq " "; - - my $bang_it; - while ( $after <= $#$ops && $ops->[$after]->[OPCODE] ne " " ) { - $bang_it ||= $ops->[$after]->[OPCODE] ne $opcode; - ++$after; - } - - if ( $bang_it ) { - for my $i ( $start..($after-1) ) { - $ops->[$i]->[FLAG] = "!"; - } - } - } - - my $b_prefixes = { "+" => "+ ", " " => " ", "-" => undef, "!" => "! " }; - my $a_prefixes = { "+" => undef, " " => " ", "-" => "- ", "!" => "! " }; - - return join( "", - "*** ", $a_range, " ****\n", - map( _op_to_line( \@_, $_, A, $a_prefixes ), @$ops ), - "--- ", $b_range, " ----\n", - map( _op_to_line( \@_, $_, B, $b_prefixes ), @$ops ), - ); -} - -@Text::Diff::OldStyle::ISA = qw( Text::Diff::Base ); - -sub _op { - my $ops = shift; - my $op = $ops->[0]->[OPCODE]; - $op = "c" if grep $_->[OPCODE] ne $op, @$ops; - $op = "a" if $op eq "+"; - $op = "d" if $op eq "-"; - return $op; -} - -sub Text::Diff::OldStyle::hunk_header { - shift; ## No instance data - pop; ## ignore options - my $ops = pop; - - my $op = _op $ops; - - return join "", _range( $ops, A, "" ), $op, _range( $ops, B, "" ), "\n"; -} - -sub Text::Diff::OldStyle::hunk { - shift; ## No instance data - pop; ## ignore options - my $ops = pop; - ## Leave the sequences in @_[0,1] - - my $a_prefixes = { "+" => undef, " " => undef, "-" => "< " }; - my $b_prefixes = { "+" => "> ", " " => undef, "-" => undef }; - - my $op = _op $ops; - - return join( "", - map( _op_to_line( \@_, $_, A, $a_prefixes ), @$ops ), - $op eq "c" ? "---\n" : (), - map( _op_to_line( \@_, $_, B, $b_prefixes ), @$ops ), - ); -} - -1; - -__END__ - -=head1 NAME - -Text::Diff - Perform diffs on files and record sets - -=head1 SYNOPSIS - - use Text::Diff; - - ## Mix and match filenames, strings, file handles, producer subs, - ## or arrays of records; returns diff in a string. - ## WARNING: can return B<large> diffs for large files. - my $diff = diff "file1.txt", "file2.txt", { STYLE => "Context" }; - my $diff = diff \$string1, \$string2, \%options; - my $diff = diff \*FH1, \*FH2; - my $diff = diff \&reader1, \&reader2; - my $diff = diff \@records1, \@records2; - - ## May also mix input types: - my $diff = diff \@records1, "file_B.txt"; - -=head1 DESCRIPTION - -C<diff()> provides a basic set of services akin to the GNU C<diff> utility. It -is not anywhere near as feature complete as GNU C<diff>, but it is better -integrated with Perl and available on all platforms. It is often faster than -shelling out to a system's C<diff> executable for small files, and generally -slower on larger files. - -Relies on L<Algorithm::Diff> for, well, the algorithm. This may not produce -the same exact diff as a system's local C<diff> executable, but it will be a -valid diff and comprehensible by C<patch>. We haven't seen any differences -between Algorithm::Diff's logic and GNU diff's, but we have not examined them -to make sure they are indeed identical. - -B<Note>: If you don't want to import the C<diff> function, do one of the -following: - - use Text::Diff (); - - require Text::Diff; - -That's a pretty rare occurence, so C<diff()> is exported by default. -=head1 OPTIONS - -diff() takes two parameters from which to draw input and a set of -options to control it's output. The options are: - -=over - -=item FILENAME_A, MTIME_A, FILENAME_B, MTIME_B - -The name of the file and the modification time "files" - -These are filled in automatically for each file when diff() is passed a -filename, unless a defined value is passed in. - -If a filename is not passed in and FILENAME_A and FILENAME_B are not provided -or C<undef>, the header will not be printed. - -Unused on C<OldStyle> diffs. - -=item OFFSET_A, OFFSET_B - -The index of the first line / element. These default to 1 for all -parameter types except ARRAY references, for which the default is 0. This -is because ARRAY references are presumed to be data structures, while the -others are line oriented text. - -=item STYLE - -"Unified", "Context", "OldStyle", or an object or class reference for a class -providing C<file_header()>, C<hunk_header()>, C<hunk()>, C<hunk_footer()> and -C<file_footer()> methods. The two footer() methods are provided for -overloading only; none of the formats provide them. - -Defaults to "Unified" (unlike standard C<diff>, but Unified is what's most -often used in submitting patches and is the most human readable of the three. - -If the package indicated by the STYLE has no hunk() method, c<diff()> will -load it automatically (lazy loading). Since all such packages should inherit -from Text::Diff::Base, this should be marvy. - -Styles may be specified as class names (C<STYLE => "Foo"), in which case they -will be C<new()>ed with no parameters, or as objects (C<STYLE => Foo->new>). - -=item CONTEXT - -How many lines before and after each diff to display. Ignored on old-style -diffs. Defaults to 3. - -=item OUTPUT - -Examples and their equivalent subroutines: - - OUTPUT => \*FOOHANDLE, # like: sub { print FOOHANDLE shift() } - OUTPUT => \$output, # like: sub { $output .= shift } - OUTPUT => \@output, # like: sub { push @output, shift } - OUTPUT => sub { $output .= shift }, - -If no C<OUTPUT> is supplied, returns the diffs in a string. If -C<OUTPUT> is a C<CODE> ref, it will be called once with the (optional) -file header, and once for each hunk body with the text to emit. If -C<OUTPUT> is an L<IO::Handle>, output will be emitted to that handle. - -=item FILENAME_PREFIX_A, FILENAME_PREFIX_B - -The string to print before the filename in the header. Unused on C<OldStyle> -diffs. Defaults are C<"---">, C<"+++"> for Unified and C<"***">, C<"+++"> for -Context. - -=item KEYGEN, KEYGEN_ARGS - -These are passed to L<Algorithm::Diff/traverse_sequences>. - -=back - -B<Note>: if neither C<FILENAME_> option is defined, the header will not be -printed. If at one is present, the other and both MTIME_ options must be -present or "Use of undefined variable" warnings will be generated (except -on C<OldStyle> diffs, which ignores these options). - -=head1 Formatting Classes - -These functions implement the output formats. They are grouped in to classes -so diff() can use class names to call the correct set of output routines and so -that you may inherit from them easily. There are no constructors or instance -methods for these classes, though subclasses may provide them if need be. - -Each class has file_header(), hunk_header(), hunk(), and footer() methods -identical to those documented in the Text::Diff::Unified section. header() is -called before the hunk() is first called, footer() afterwards. The default -footer function is an empty method provided for overloading: - - sub footer { return "End of patch\n" } - -Some output formats are provided by external modules (which are loaded -automatically), such as L<Text::Diff::Table>. These are -are documented here to keep the documentation simple. - -=head2 Text::Diff::Base - -Returns "" for all methods (other than C<new()>). - -=head2 Text::Diff::Unified - - --- A Mon Nov 12 23:49:30 2001 - +++ B Mon Nov 12 23:49:30 2001 - @@ -2,13 +2,13 @@ - 2 - 3 - 4 - -5d - +5a - 6 - 7 - 8 - 9 - +9a - 10 - 11 - -11d - 12 - 13 - -=over - -=item file_header - - $s = Text::Diff::Unified->file_header( $options ); - -Returns a string containing a unified header. The sole parameter is the -options hash passed in to diff(), containing at least: - - FILENAME_A => $fn1, - MTIME_A => $mtime1, - FILENAME_B => $fn2, - MTIME_B => $mtime2 - -May also contain - - FILENAME_PREFIX_A => "---", - FILENAME_PREFIX_B => "+++", - -to override the default prefixes (default values shown). - -=item hunk_header - - Text::Diff::Unified->hunk_header( \@ops, $options ); - -Returns a string containing the output of one hunk of unified diff. - -=item Text::Diff::Unified::hunk - - Text::Diff::Unified->hunk( \@seq_a, \@seq_b, \@ops, $options ); - -Returns a string containing the output of one hunk of unified diff. - -=back - -=head2 Text::Diff::Table - - +--+----------------------------------+--+------------------------------+ - | |../Test-Differences-0.2/MANIFEST | |../Test-Differences/MANIFEST | - | |Thu Dec 13 15:38:49 2001 | |Sat Dec 15 02:09:44 2001 | - +--+----------------------------------+--+------------------------------+ - | | * 1|Changes * - | 1|Differences.pm | 2|Differences.pm | - | 2|MANIFEST | 3|MANIFEST | - | | * 4|MANIFEST.SKIP * - | 3|Makefile.PL | 5|Makefile.PL | - | | * 6|t/00escape.t * - | 4|t/00flatten.t | 7|t/00flatten.t | - | 5|t/01text_vs_data.t | 8|t/01text_vs_data.t | - | 6|t/10test.t | 9|t/10test.t | - +--+----------------------------------+--+------------------------------+ - -This format also goes to some pains to highlight "invisible" characters on -differing elements by selectively escaping whitespace: - - +--+--------------------------+--------------------------+ - | |demo_ws_A.txt |demo_ws_B.txt | - | |Fri Dec 21 08:36:32 2001 |Fri Dec 21 08:36:50 2001 | - +--+--------------------------+--------------------------+ - | 1|identical |identical | - * 2| spaced in | also spaced in * - * 3|embedded space |embedded tab * - | 4|identical |identical | - * 5| spaced in |\ttabbed in * - * 6|trailing spaces\s\s\n |trailing tabs\t\t\n * - | 7|identical |identical | - * 8|lf line\n |crlf line\r\n * - * 9|embedded ws |embedded\tws * - +--+--------------------------+--------------------------+ - -See L</Text::Diff::Table> for more details, including how the whitespace -escaping works. - -=head2 Text::Diff::Context - - *** A Mon Nov 12 23:49:30 2001 - --- B Mon Nov 12 23:49:30 2001 - *************** - *** 2,14 **** - 2 - 3 - 4 - ! 5d - 6 - 7 - 8 - 9 - 10 - 11 - - 11d - 12 - 13 - --- 2,14 ---- - 2 - 3 - 4 - ! 5a - 6 - 7 - 8 - 9 - + 9a - 10 - 11 - 12 - 13 - -Note: hunk_header() returns only "***************\n". - -=head2 Text::Diff::OldStyle - - 5c5 - < 5d - --- - > 5a - 9a10 - > 9a - 12d12 - < 11d - -Note: no file_header(). - -=head1 LIMITATIONS - -Must suck both input files entirely in to memory and store them with a normal -amount of Perlish overhead (one array location) per record. This is implied by -the implementation of Algorithm::Diff, which takes two arrays. If -Algorithm::Diff ever offers an incremental mode, this can be changed (contact -the maintainers of Algorithm::Diff and Text::Diff if you need this; it -shouldn't be too terribly hard to tie arrays in this fashion). - -Does not provide most of the more refined GNU diff options: recursive directory -tree scanning, ignoring blank lines / whitespace, etc., etc. These can all be -added as time permits and need arises, many are rather easy; patches quite -welcome. - -Uses closures internally, this may lead to leaks on C<perl> versions 5.6.1 and -prior if used many times over a process' life time. - -=head1 AUTHOR - -Adam Kennedy E<lt>adamk@cpan.orgE<gt> - -Barrie Slaymaker E<lt>barries@slaysys.comE<gt> - -=head1 COPYRIGHT - -Some parts copyright 2009 Adam Kennedy. - -Copyright 2001 Barrie Slaymaker. All Rights Reserved. - -You may use this under the terms of either the Artistic License or GNU Public -License v 2.0 or greater. - -=cut - -1; diff --git a/Master/tlpkg/tlperl/lib/Text/Diff/Table.pm b/Master/tlpkg/tlperl/lib/Text/Diff/Table.pm deleted file mode 100755 index c34ef2c9664..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Diff/Table.pm +++ /dev/null @@ -1,408 +0,0 @@ -package Text::Diff::Table; - -use 5.00503; -use strict; -use Carp; -use vars qw{$VERSION @ISA @EXPORT_OK}; -BEGIN { - $VERSION = '1.37'; - @ISA = qw( Text::Diff::Base Exporter ); - @EXPORT_OK = qw( expand_tabs ); -} - -my %escapes = map { - my $c = - $_ eq '"' || $_ eq '$' ? qq{'$_'} - : $_ eq "\\" ? qq{"\\\\"} - : qq{"$_"}; - ( ord eval $c => $_ ) -} ( - map( chr, 32..126), - map( sprintf( "\\x%02x", $_ ), ( 0..31, 127..255 ) ), -# map( "\\c$_", "A".."Z"), - "\\t", "\\n", "\\r", "\\f", "\\b", "\\a", "\\e" - ## NOTE: "\\\\" is not here because some things are explicitly - ## escaped before escape() is called and we don't want to - ## double-escape "\". Also, in most texts, leaving "\" more - ## readable makes sense. -); - -sub expand_tabs($) { - my $s = shift; - my $count = 0; - $s =~ s{(\t)(\t*)|([^\t]+)}{ - if ( $1 ) { - my $spaces = " " x ( 8 - $count % 8 + 8 * length $2 ); - $count = 0; - $spaces; - } - else { - $count += length $3; - $3; - } - }ge; - - return $s; -} - -sub trim_trailing_line_ends($) { - my $s = shift; - $s =~ s/[\r\n]+(?!\n)$//; - return $s; -} - -sub escape($); - -SCOPE: { - ## use utf8 if available. don't if not. - my $escaper = <<'EOCODE'; - sub escape($) { - use utf8; - join "", map { - $_ = ord; - exists $escapes{$_} - ? $escapes{$_} - : sprintf( "\\x{%04x}", $_ ); - } split //, shift; - } - - 1; -EOCODE - unless ( eval $escaper ) { - $escaper =~ s/ *use *utf8 *;\n// or die "Can't drop use utf8;"; - eval $escaper or die $@; - } -} - -sub new { - my $proto = shift; - return bless { @_ }, $proto -} - -my $missing_elt = [ "", "" ]; - -sub hunk { - my $self = shift; - my @seqs = ( shift, shift ); - my $ops = shift; ## Leave sequences in @_[0,1] - my $options = shift; - - my ( @A, @B ); - for ( @$ops ) { - my $opcode = $_->[Text::Diff::OPCODE()]; - if ( $opcode eq " " ) { - push @A, $missing_elt while @A < @B; - push @B, $missing_elt while @B < @A; - } - push @A, [ $_->[0] + ( $options->{OFFSET_A} || 0), $seqs[0][$_->[0]] ] - if $opcode eq " " || $opcode eq "-"; - push @B, [ $_->[1] + ( $options->{OFFSET_B} || 0), $seqs[1][$_->[1]] ] - if $opcode eq " " || $opcode eq "+"; - } - - push @A, $missing_elt while @A < @B; - push @B, $missing_elt while @B < @A; - my @elts; - for ( 0..$#A ) { - my ( $A, $B ) = (shift @A, shift @B ); - - ## Do minimal cleaning on identical elts so these look "normal": - ## tabs are expanded, trailing newelts removed, etc. For differing - ## elts, make invisible characters visible if the invisible characters - ## differ. - my $elt_type = $B == $missing_elt ? "A" : - $A == $missing_elt ? "B" : - $A->[1] eq $B->[1] ? "=" - : "*"; - if ( $elt_type ne "*" ) { - if ( $elt_type eq "=" || $A->[1] =~ /\S/ || $B->[1] =~ /\S/ ) { - $A->[1] = escape trim_trailing_line_ends expand_tabs $A->[1]; - $B->[1] = escape trim_trailing_line_ends expand_tabs $B->[1]; - } - else { - $A->[1] = escape $A->[1]; - $B->[1] = escape $B->[1]; - } - } - else { - ## not using \z here for backcompat reasons. - $A->[1] =~ /^(\s*?)([^ \t].*?)?(\s*)(?![\n\r])$/s; - my ( $l_ws_A, $body_A, $t_ws_A ) = ( $1, $2, $3 ); - $body_A = "" unless defined $body_A; - $B->[1] =~ /^(\s*?)([^ \t].*?)?(\s*)(?![\n\r])$/s; - my ( $l_ws_B, $body_B, $t_ws_B ) = ( $1, $2, $3 ); - $body_B = "" unless defined $body_B; - - my $added_escapes; - - if ( $l_ws_A ne $l_ws_B ) { - ## Make leading tabs visible. Other non-' ' chars - ## will be dealt with in escape(), but this prevents - ## tab expansion from hiding tabs by making them - ## look like ' '. - $added_escapes = 1 if $l_ws_A =~ s/\t/\\t/g; - $added_escapes = 1 if $l_ws_B =~ s/\t/\\t/g; - } - - if ( $t_ws_A ne $t_ws_B ) { - ## Only trailing whitespace gets the \s treatment - ## to make it obvious what's going on. - $added_escapes = 1 if $t_ws_A =~ s/ /\\s/g; - $added_escapes = 1 if $t_ws_B =~ s/ /\\s/g; - $added_escapes = 1 if $t_ws_A =~ s/\t/\\t/g; - $added_escapes = 1 if $t_ws_B =~ s/\t/\\t/g; - } - else { - $t_ws_A = $t_ws_B = ""; - } - - my $do_tab_escape = $added_escapes || do { - my $expanded_A = expand_tabs join( $body_A, $l_ws_A, $t_ws_A ); - my $expanded_B = expand_tabs join( $body_B, $l_ws_B, $t_ws_B ); - $expanded_A eq $expanded_B; - }; - - my $do_back_escape = $do_tab_escape || do { - my ( $unescaped_A, $escaped_A, - $unescaped_B, $escaped_B - ) = - map - join( "", /(\\.)/g ), - map { - ( $_, escape $_ ) - } - expand_tabs join( $body_A, $l_ws_A, $t_ws_A ), - expand_tabs join( $body_B, $l_ws_B, $t_ws_B ); - $unescaped_A ne $unescaped_B && $escaped_A eq $escaped_B; - }; - - if ( $do_back_escape ) { - $body_A =~ s/\\/\\\\/g; - $body_B =~ s/\\/\\\\/g; - } - - my $line_A = join $body_A, $l_ws_A, $t_ws_A; - my $line_B = join $body_B, $l_ws_B, $t_ws_B; - - unless ( $do_tab_escape ) { - $line_A = expand_tabs $line_A; - $line_B = expand_tabs $line_B; - } - - $A->[1] = escape $line_A; - $B->[1] = escape $line_B; - } - - push @elts, [ @$A, @$B, $elt_type ]; - } - - push @{$self->{ELTS}}, @elts, ["bar"]; - return ""; -} - -sub _glean_formats { - my $self = shift; -} - -sub file_footer { - my $self = shift; - my @seqs = (shift,shift); - my $options = pop; - - my @heading_lines; - - if ( defined $options->{FILENAME_A} || defined $options->{FILENAME_B} ) { - push @heading_lines, [ - map( - { - ( "", escape( defined $_ ? $_ : "<undef>" ) ); - } - ( @{$options}{qw( FILENAME_A FILENAME_B)} ) - ), - "=", - ]; - } - - if ( defined $options->{MTIME_A} || defined $options->{MTIME_B} ) { - push @heading_lines, [ - map( { - ( "", - escape( - ( defined $_ && length $_ ) - ? localtime $_ - : "" - ) - ); - } - @{$options}{qw( MTIME_A MTIME_B )} - ), - "=", - ]; - } - - if ( defined $options->{INDEX_LABEL} ) { - push @heading_lines, [ "", "", "", "", "=" ] unless @heading_lines; - $heading_lines[-1]->[0] = $heading_lines[-1]->[2] = - $options->{INDEX_LABEL}; - } - - ## Not ushifting on to @{$self->{ELTS}} in case it's really big. Want - ## to avoid the overhead. - - my $four_column_mode = 0; - for my $cols ( @heading_lines, @{$self->{ELTS}} ) { - next if $cols->[-1] eq "bar"; - if ( $cols->[0] ne $cols->[2] ) { - $four_column_mode = 1; - last; - } - } - - unless ( $four_column_mode ) { - for my $cols ( @heading_lines, @{$self->{ELTS}} ) { - next if $cols->[-1] eq "bar"; - splice @$cols, 2, 1; - } - } - - my @w = (0,0,0,0); - for my $cols ( @heading_lines, @{$self->{ELTS}} ) { - next if $cols->[-1] eq "bar"; - for my $i (0..($#$cols-1)) { - $w[$i] = length $cols->[$i] - if defined $cols->[$i] && length $cols->[$i] > $w[$i]; - } - } - - my %fmts = $four_column_mode - ? ( - "=" => "| %$w[0]s|%-$w[1]s | %$w[2]s|%-$w[3]s |\n", - "A" => "* %$w[0]s|%-$w[1]s * %$w[2]s|%-$w[3]s |\n", - "B" => "| %$w[0]s|%-$w[1]s * %$w[2]s|%-$w[3]s *\n", - "*" => "* %$w[0]s|%-$w[1]s * %$w[2]s|%-$w[3]s *\n", - ) - : ( - "=" => "| %$w[0]s|%-$w[1]s |%-$w[2]s |\n", - "A" => "* %$w[0]s|%-$w[1]s |%-$w[2]s |\n", - "B" => "| %$w[0]s|%-$w[1]s |%-$w[2]s *\n", - "*" => "* %$w[0]s|%-$w[1]s |%-$w[2]s *\n", - ); - - $fmts{bar} = sprintf $fmts{"="}, "", "", "", ""; - $fmts{bar} =~ s/\S/+/g; - $fmts{bar} =~ s/ /-/g; - return join( "", - map { - sprintf( $fmts{$_->[-1]}, @$_ ) - } ( - ["bar"], - @heading_lines, - @heading_lines ? ["bar"] : (), - @{$self->{ELTS}}, - ), - ); - - @{$self->{ELTS}} = []; -} - -1; - -__END__ - -=pod - -=head1 NAME - - Text::Diff::Table - Text::Diff plugin to generate "table" format output - -=head1 SYNOPSIS - - use Text::Diff; - - diff \@a, $b { STYLE => "Table" }; - -=head1 DESCRIPTION - -This is a plugin output formatter for Text::Diff that generates "table" style -diffs: - - +--+----------------------------------+--+------------------------------+ - | |../Test-Differences-0.2/MANIFEST | |../Test-Differences/MANIFEST | - | |Thu Dec 13 15:38:49 2001 | |Sat Dec 15 02:09:44 2001 | - +--+----------------------------------+--+------------------------------+ - | | * 1|Changes * - | 1|Differences.pm | 2|Differences.pm | - | 2|MANIFEST | 3|MANIFEST | - | | * 4|MANIFEST.SKIP * - | 3|Makefile.PL | 5|Makefile.PL | - | | * 6|t/00escape.t * - | 4|t/00flatten.t | 7|t/00flatten.t | - | 5|t/01text_vs_data.t | 8|t/01text_vs_data.t | - | 6|t/10test.t | 9|t/10test.t | - +--+----------------------------------+--+------------------------------+ - -This format also goes to some pains to highlight "invisible" characters on -differing elements by selectively escaping whitespace. Each element is split -in to three segments (leading whitespace, body, trailing whitespace). If -whitespace differs in a segement, that segment is whitespace escaped. - -Here is an example of the selective whitespace. - - +--+--------------------------+--------------------------+ - | |demo_ws_A.txt |demo_ws_B.txt | - | |Fri Dec 21 08:36:32 2001 |Fri Dec 21 08:36:50 2001 | - +--+--------------------------+--------------------------+ - | 1|identical |identical | - * 2| spaced in | also spaced in * - * 3|embedded space |embedded tab * - | 4|identical |identical | - * 5| spaced in |\ttabbed in * - * 6|trailing spaces\s\s\n |trailing tabs\t\t\n * - | 7|identical |identical | - * 8|lf line\n |crlf line\r\n * - * 9|embedded ws |embedded\tws * - +--+--------------------------+--------------------------+ - -Here's why the lines do or do not have whitespace escaped: - -=over - -=item lines 1, 4, 7 don't differ, no need. - -=item lines 2, 3 differ in non-whitespace, no need. - -=item lines 5, 6, 8, 9 all have subtle ws changes. - -=back - -Whether or not line 3 should have that tab character escaped is a judgement -call; so far I'm choosing not to. - -=head1 LIMITATIONS - -Table formatting requires buffering the entire diff in memory in order to -calculate column widths. This format should only be used for smaller -diffs. - -Assumes tab stops every 8 characters, as $DIETY intended. - -Assumes all character codes >= 127 need to be escaped as hex codes, ie that the -user's terminal is ASCII, and not even "high bit ASCII", capable. This can be -made an option when the need arises. - -Assumes that control codes (character codes 0..31) that don't have slash-letter -escapes ("\n", "\r", etc) in Perl are best presented as hex escapes ("\x01") -instead of octal ("\001") or control-code ("\cA") escapes. - -=head1 AUTHOR - -Barrie Slaymaker E<lt>barries@slaysys.comE<gt> - -=head1 LICENSE - -Copyright 2001 Barrie Slaymaker, All Rights Reserved. - -You may use this software under the terms of the GNU public license, any -version, or the Artistic license. - -=cut diff --git a/Master/tlpkg/tlperl/lib/Text/Glob.pm b/Master/tlpkg/tlperl/lib/Text/Glob.pm deleted file mode 100755 index 2d3436f1ac1..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Glob.pm +++ /dev/null @@ -1,195 +0,0 @@ -package Text::Glob; -use strict; -use Exporter; -use vars qw/$VERSION @ISA @EXPORT_OK - $strict_leading_dot $strict_wildcard_slash/; -$VERSION = '0.08'; -@ISA = 'Exporter'; -@EXPORT_OK = qw( glob_to_regex glob_to_regex_string match_glob ); - -$strict_leading_dot = 1; -$strict_wildcard_slash = 1; - -use constant debug => 0; - -sub glob_to_regex { - my $glob = shift; - my $regex = glob_to_regex_string($glob); - return qr/^$regex$/; -} - -sub glob_to_regex_string -{ - my $glob = shift; - my ($regex, $in_curlies, $escaping); - local $_; - my $first_byte = 1; - for ($glob =~ m/(.)/gs) { - if ($first_byte) { - if ($strict_leading_dot) { - $regex .= '(?=[^\.])' unless $_ eq '.'; - } - $first_byte = 0; - } - if ($_ eq '/') { - $first_byte = 1; - } - if ($_ eq '.' || $_ eq '(' || $_ eq ')' || $_ eq '|' || - $_ eq '+' || $_ eq '^' || $_ eq '$' || $_ eq '@' || $_ eq '%' ) { - $regex .= "\\$_"; - } - elsif ($_ eq '*') { - $regex .= $escaping ? "\\*" : - $strict_wildcard_slash ? "[^/]*" : ".*"; - } - elsif ($_ eq '?') { - $regex .= $escaping ? "\\?" : - $strict_wildcard_slash ? "[^/]" : "."; - } - elsif ($_ eq '{') { - $regex .= $escaping ? "\\{" : "("; - ++$in_curlies unless $escaping; - } - elsif ($_ eq '}' && $in_curlies) { - $regex .= $escaping ? "}" : ")"; - --$in_curlies unless $escaping; - } - elsif ($_ eq ',' && $in_curlies) { - $regex .= $escaping ? "," : "|"; - } - elsif ($_ eq "\\") { - if ($escaping) { - $regex .= "\\\\"; - $escaping = 0; - } - else { - $escaping = 1; - } - next; - } - else { - $regex .= $_; - $escaping = 0; - } - $escaping = 0; - } - print "# $glob $regex\n" if debug; - - return $regex; -} - -sub match_glob { - print "# ", join(', ', map { "'$_'" } @_), "\n" if debug; - my $glob = shift; - my $regex = glob_to_regex $glob; - local $_; - grep { $_ =~ $regex } @_; -} - -1; -__END__ - -=head1 NAME - -Text::Glob - match globbing patterns against text - -=head1 SYNOPSIS - - use Text::Glob qw( match_glob glob_to_regex ); - - print "matched\n" if match_glob( "foo.*", "foo.bar" ); - - # prints foo.bar and foo.baz - my $regex = glob_to_regex( "foo.*" ); - for ( qw( foo.bar foo.baz foo bar ) ) { - print "matched: $_\n" if /$regex/; - } - -=head1 DESCRIPTION - -Text::Glob implements glob(3) style matching that can be used to match -against text, rather than fetching names from a filesystem. If you -want to do full file globbing use the File::Glob module instead. - -=head2 Routines - -=over - -=item match_glob( $glob, @things_to_test ) - -Returns the list of things which match the glob from the source list. - -=item glob_to_regex( $glob ) - -Returns a compiled regex which is the equiavlent of the globbing -pattern. - -=item glob_to_regex_string( $glob ) - -Returns a regex string which is the equiavlent of the globbing -pattern. - -=back - -=head1 SYNTAX - -The following metacharacters and rules are respected. - -=over - -=item C<*> - match zero or more characters - -C<a*> matches C<a>, C<aa>, C<aaaa> and many many more. - -=item C<?> - match exactly one character - -C<a?> matches C<aa>, but not C<a>, or C<aa> - -=item Character sets/ranges - -C<example.[ch]> matches C<example.c> and C<example.h> - -C<demo.[a-c]> matches C<demo.a>, C<demo.b>, and C<demo.c> - -=item alternation - -C<example.{foo,bar,baz}> matches C<example.foo>, C<example.bar>, and -C<example.baz> - -=item leading . must be explictly matched - -C<*.foo> does not match C<.bar.foo>. For this you must either specify -the leading . in the glob pattern (C<.*.foo>), or set -C<$Text::Glob::strict_leading_dot> to a false value while compiling -the regex. - -=item C<*> and C<?> do not match / - -C<*.foo> does not match C<bar/baz.foo>. For this you must either -explicitly match the / in the glob (C<*/*.foo>), or set -C<$Text::Glob::strict_wildcard_slash> to a false value with compiling -the regex. - -=back - -=head1 BUGS - -The code uses qr// to produce compiled regexes, therefore this module -requires perl version 5.005_03 or newer. - -=head1 AUTHOR - -Richard Clamp <richardc@unixbeard.net> - -=head1 COPYRIGHT - -Copyright (C) 2002, 2003, 2006, 2007 Richard Clamp. All Rights Reserved. - -This module is free software; you can redistribute it and/or modify it -under the same terms as Perl itself. - -=head1 SEE ALSO - -L<File::Glob>, glob(3) - -=cut diff --git a/Master/tlpkg/tlperl/lib/Text/ParseWords.pm b/Master/tlpkg/tlperl/lib/Text/ParseWords.pm deleted file mode 100755 index f1b5937904e..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/ParseWords.pm +++ /dev/null @@ -1,294 +0,0 @@ -package Text::ParseWords; - -use strict; -require 5.006; -our $VERSION = "3.27"; - - -use Exporter; -our @ISA = qw(Exporter); -our @EXPORT = qw(shellwords quotewords nested_quotewords parse_line); -our @EXPORT_OK = qw(old_shellwords); -our $PERL_SINGLE_QUOTE; - - -sub shellwords { - my (@lines) = @_; - my @allwords; - - foreach my $line (@lines) { - $line =~ s/^\s+//; - my @words = parse_line('\s+', 0, $line); - pop @words if (@words and !defined $words[-1]); - return() unless (@words || !length($line)); - push(@allwords, @words); - } - return(@allwords); -} - - - -sub quotewords { - my($delim, $keep, @lines) = @_; - my($line, @words, @allwords); - - foreach $line (@lines) { - @words = parse_line($delim, $keep, $line); - return() unless (@words || !length($line)); - push(@allwords, @words); - } - return(@allwords); -} - - - -sub nested_quotewords { - my($delim, $keep, @lines) = @_; - my($i, @allwords); - - for ($i = 0; $i < @lines; $i++) { - @{$allwords[$i]} = parse_line($delim, $keep, $lines[$i]); - return() unless (@{$allwords[$i]} || !length($lines[$i])); - } - return(@allwords); -} - - - -sub parse_line { - my($delimiter, $keep, $line) = @_; - my($word, @pieces); - - no warnings 'uninitialized'; # we will be testing undef strings - - while (length($line)) { - # This pattern is optimised to be stack conservative on older perls. - # Do not refactor without being careful and testing it on very long strings. - # See Perl bug #42980 for an example of a stack busting input. - $line =~ s/^ - (?: - # double quoted string - (") # $quote - ((?>[^\\"]*(?:\\.[^\\"]*)*))" # $quoted - | # --OR-- - # singe quoted string - (') # $quote - ((?>[^\\']*(?:\\.[^\\']*)*))' # $quoted - | # --OR-- - # unquoted string - ( # $unquoted - (?:\\.|[^\\"'])*? - ) - # followed by - ( # $delim - \Z(?!\n) # EOL - | # --OR-- - (?-x:$delimiter) # delimiter - | # --OR-- - (?!^)(?=["']) # a quote - ) - )//xs or return; # extended layout - my ($quote, $quoted, $unquoted, $delim) = (($1 ? ($1,$2) : ($3,$4)), $5, $6); - - - return() unless( defined($quote) || length($unquoted) || length($delim)); - - if ($keep) { - $quoted = "$quote$quoted$quote"; - } - else { - $unquoted =~ s/\\(.)/$1/sg; - if (defined $quote) { - $quoted =~ s/\\(.)/$1/sg if ($quote eq '"'); - $quoted =~ s/\\([\\'])/$1/g if ( $PERL_SINGLE_QUOTE && $quote eq "'"); - } - } - $word .= substr($line, 0, 0); # leave results tainted - $word .= defined $quote ? $quoted : $unquoted; - - if (length($delim)) { - push(@pieces, $word); - push(@pieces, $delim) if ($keep eq 'delimiters'); - undef $word; - } - if (!length($line)) { - push(@pieces, $word); - } - } - return(@pieces); -} - - - -sub old_shellwords { - - # Usage: - # use ParseWords; - # @words = old_shellwords($line); - # or - # @words = old_shellwords(@lines); - # or - # @words = old_shellwords(); # defaults to $_ (and clobbers it) - - no warnings 'uninitialized'; # we will be testing undef strings - local *_ = \join('', @_) if @_; - my (@words, $snippet); - - s/\A\s+//; - while ($_ ne '') { - my $field = substr($_, 0, 0); # leave results tainted - for (;;) { - if (s/\A"(([^"\\]|\\.)*)"//s) { - ($snippet = $1) =~ s#\\(.)#$1#sg; - } - elsif (/\A"/) { - require Carp; - Carp::carp("Unmatched double quote: $_"); - return(); - } - elsif (s/\A'(([^'\\]|\\.)*)'//s) { - ($snippet = $1) =~ s#\\(.)#$1#sg; - } - elsif (/\A'/) { - require Carp; - Carp::carp("Unmatched single quote: $_"); - return(); - } - elsif (s/\A\\(.?)//s) { - $snippet = $1; - } - elsif (s/\A([^\s\\'"]+)//) { - $snippet = $1; - } - else { - s/\A\s+//; - last; - } - $field .= $snippet; - } - push(@words, $field); - } - return @words; -} - -1; - -__END__ - -=head1 NAME - -Text::ParseWords - parse text into an array of tokens or array of arrays - -=head1 SYNOPSIS - - use Text::ParseWords; - @lists = nested_quotewords($delim, $keep, @lines); - @words = quotewords($delim, $keep, @lines); - @words = shellwords(@lines); - @words = parse_line($delim, $keep, $line); - @words = old_shellwords(@lines); # DEPRECATED! - -=head1 DESCRIPTION - -The &nested_quotewords() and "ewords() functions accept a delimiter -(which can be a regular expression) -and a list of lines and then breaks those lines up into a list of -words ignoring delimiters that appear inside quotes. "ewords() -returns all of the tokens in a single long list, while &nested_quotewords() -returns a list of token lists corresponding to the elements of @lines. -&parse_line() does tokenizing on a single string. The &*quotewords() -functions simply call &parse_line(), so if you're only splitting -one line you can call &parse_line() directly and save a function -call. - -The $keep argument is a boolean flag. If true, then the tokens are -split on the specified delimiter, but all other characters (quotes, -backslashes, etc.) are kept in the tokens. If $keep is false then the -&*quotewords() functions remove all quotes and backslashes that are -not themselves backslash-escaped or inside of single quotes (i.e., -"ewords() tries to interpret these characters just like the Bourne -shell). NB: these semantics are significantly different from the -original version of this module shipped with Perl 5.000 through 5.004. -As an additional feature, $keep may be the keyword "delimiters" which -causes the functions to preserve the delimiters in each string as -tokens in the token lists, in addition to preserving quote and -backslash characters. - -&shellwords() is written as a special case of "ewords(), and it -does token parsing with whitespace as a delimiter-- similar to most -Unix shells. - -=head1 EXAMPLES - -The sample program: - - use Text::ParseWords; - @words = quotewords('\s+', 0, q{this is "a test" of\ quotewords \"for you}); - $i = 0; - foreach (@words) { - print "$i: <$_>\n"; - $i++; - } - -produces: - - 0: <this> - 1: <is> - 2: <a test> - 3: <of quotewords> - 4: <"for> - 5: <you> - -demonstrating: - -=over 4 - -=item 0 - -a simple word - -=item 1 - -multiple spaces are skipped because of our $delim - -=item 2 - -use of quotes to include a space in a word - -=item 3 - -use of a backslash to include a space in a word - -=item 4 - -use of a backslash to remove the special meaning of a double-quote - -=item 5 - -another simple word (note the lack of effect of the -backslashed double-quote) - -=back - -Replacing C<quotewords('\s+', 0, q{this is...})> -with C<shellwords(q{this is...})> -is a simpler way to accomplish the same thing. - -=head1 AUTHORS - -Maintainer: Alexandr Ciornii <alexchornyATgmail.com>. - -Previous maintainer: Hal Pomeranz <pomeranz@netcom.com>, 1994-1997 (Original -author unknown). Much of the code for &parse_line() (including the -primary regexp) from Joerk Behrends <jbehrends@multimediaproduzenten.de>. - -Examples section another documentation provided by John Heidemann -<johnh@ISI.EDU> - -Bug reports, patches, and nagging provided by lots of folks-- thanks -everybody! Special thanks to Michael Schwern <schwern@envirolink.org> -for assuring me that a &nested_quotewords() would be useful, and to -Jeff Friedl <jfriedl@yahoo-inc.com> for telling me not to worry about -error-checking (sort of-- you had to be there). - -=cut diff --git a/Master/tlpkg/tlperl/lib/Text/Soundex.pm b/Master/tlpkg/tlperl/lib/Text/Soundex.pm deleted file mode 100755 index 5d702200164..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Soundex.pm +++ /dev/null @@ -1,260 +0,0 @@ -# -*- perl -*- - -# (c) Copyright 1998-2007 by Mark Mielke -# -# Freedom to use these sources for whatever you want, as long as credit -# is given where credit is due, is hereby granted. You may make modifications -# where you see fit but leave this copyright somewhere visible. As well, try -# to initial any changes you make so that if I like the changes I can -# incorporate them into later versions. -# -# - Mark Mielke <mark@mielke.cc> -# - -package Text::Soundex; -require 5.006; - -use Exporter (); -use XSLoader (); - -use strict; - -our $VERSION = '3.03'; -our @EXPORT_OK = qw(soundex soundex_unicode soundex_nara soundex_nara_unicode - $soundex_nocode); -our @EXPORT = qw(soundex soundex_nara $soundex_nocode); -our @ISA = qw(Exporter); - -our $nocode; - -# Previous releases of Text::Soundex made $nocode available as $soundex_nocode. -# For now, this part of the interface is exported and maintained. -# In the feature, $soundex_nocode will be deprecated. -*Text::Soundex::soundex_nocode = \$nocode; - -sub soundex_noxs -{ - # Original Soundex algorithm - - my @results = map { - my $code = uc($_); - $code =~ tr/AaEeHhIiOoUuWwYyBbFfPpVvCcGgJjKkQqSsXxZzDdTtLlMmNnRr//cd; - - if (length($code)) { - my $firstchar = substr($code, 0, 1); - $code =~ tr[AaEeHhIiOoUuWwYyBbFfPpVvCcGgJjKkQqSsXxZzDdTtLlMmNnRr] - [0000000000000000111111112222222222222222333344555566]s; - ($code = substr($code, 1)) =~ tr/0//d; - substr($firstchar . $code . '000', 0, 4); - } else { - $nocode; - } - } @_; - - wantarray ? @results : $results[0]; -} - -sub soundex_nara -{ - # US census (NARA) algorithm. - - my @results = map { - my $code = uc($_); - $code =~ tr/AaEeHhIiOoUuWwYyBbFfPpVvCcGgJjKkQqSsXxZzDdTtLlMmNnRr//cd; - - if (length($code)) { - my $firstchar = substr($code, 0, 1); - $code =~ tr[AaEeHhIiOoUuWwYyBbFfPpVvCcGgJjKkQqSsXxZzDdTtLlMmNnRr] - [0000990000009900111111112222222222222222333344555566]s; - $code =~ s/(.)9\1/$1/gs; - ($code = substr($code, 1)) =~ tr/09//d; - substr($firstchar . $code . '000', 0, 4); - } else { - $nocode - } - } @_; - - wantarray ? @results : $results[0]; -} - -sub soundex_unicode -{ - require Text::Unidecode unless defined &Text::Unidecode::unidecode; - soundex(Text::Unidecode::unidecode(@_)); -} - -sub soundex_nara_unicode -{ - require Text::Unidecode unless defined &Text::Unidecode::unidecode; - soundex_nara(Text::Unidecode::unidecode(@_)); -} - -eval { XSLoader::load(__PACKAGE__, $VERSION) }; - -if (defined(&soundex_xs)) { - *soundex = \&soundex_xs; -} else { - *soundex = \&soundex_noxs; - *soundex_xs = sub { - require Carp; - Carp::croak("XS implementation of Text::Soundex::soundex_xs() ". - "could not be loaded"); - }; -} - -1; - -__END__ - -# Implementation of the soundex algorithm. -# -# Some of this documention was written by Mike Stok. -# -# Examples: -# -# Euler, Ellery -> E460 -# Gauss, Ghosh -> G200 -# Hilbert, Heilbronn -> H416 -# Knuth, Kant -> K530 -# Lloyd, Ladd -> L300 -# Lukasiewicz, Lissajous -> L222 -# - -=head1 NAME - -Text::Soundex - Implementation of the soundex algorithm. - -=head1 SYNOPSIS - - use Text::Soundex; - - # Original algorithm. - $code = soundex($name); # Get the soundex code for a name. - @codes = soundex(@names); # Get the list of codes for a list of names. - - # American Soundex variant (NARA) - Used for US census data. - $code = soundex_nara($name); # Get the soundex code for a name. - @codes = soundex_nara(@names); # Get the list of codes for a list of names. - - # Redefine the value that soundex() will return if the input string - # contains no identifiable sounds within it. - $Text::Soundex::nocode = 'Z000'; - -=head1 DESCRIPTION - -Soundex is a phonetic algorithm for indexing names by sound, as -pronounced in English. The goal is for names with the same -pronunciation to be encoded to the same representation so that they -can be matched despite minor differences in spelling. Soundex is the -most widely known of all phonetic algorithms and is often used -(incorrectly) as a synonym for "phonetic algorithm". Improvements to -Soundex are the basis for many modern phonetic algorithms. (Wikipedia, -2007) - -This module implements the original soundex algorithm developed by -Robert Russell and Margaret Odell, patented in 1918 and 1922, as well -as a variation called "American Soundex" used for US census data, and -current maintained by the National Archives and Records Administration -(NARA). - -The soundex algorithm may be recognized from Donald Knuth's -B<The Art of Computer Programming>. The algorithm described by -Knuth is the NARA algorithm. - -The value returned for strings which have no soundex encoding is -defined using C<$Text::Soundex::nocode>. The default value is C<undef>, -however values such as C<'Z000'> are commonly used alternatives. - -For backward compatibility with older versions of this module the -C<$Text::Soundex::nocode> is exported into the caller's namespace as -C<$soundex_nocode>. - -In scalar context, C<soundex()> returns the soundex code of its first -argument. In list context, a list is returned in which each element is the -soundex code for the corresponding argument passed to C<soundex()>. For -example, the following code assigns @codes the value C<('M200', 'S320')>: - - @codes = soundex qw(Mike Stok); - -To use C<Text::Soundex> to generate codes that can be used to search one -of the publically available US Censuses, a variant of the soundex -algorithm must be used: - - use Text::Soundex; - $code = soundex_nara($name); - -An example of where these algorithm differ follows: - - use Text::Soundex; - print soundex("Ashcraft"), "\n"; # prints: A226 - print soundex_nara("Ashcraft"), "\n"; # prints: A261 - -=head1 EXAMPLES - -Donald Knuth's examples of names and the soundex codes they map to -are listed below: - - Euler, Ellery -> E460 - Gauss, Ghosh -> G200 - Hilbert, Heilbronn -> H416 - Knuth, Kant -> K530 - Lloyd, Ladd -> L300 - Lukasiewicz, Lissajous -> L222 - -so: - - $code = soundex 'Knuth'; # $code contains 'K530' - @list = soundex qw(Lloyd Gauss); # @list contains 'L300', 'G200' - -=head1 LIMITATIONS - -As the soundex algorithm was originally used a B<long> time ago in the US -it considers only the English alphabet and pronunciation. In particular, -non-ASCII characters will be ignored. The recommended method of dealing -with characters that have accents, or other unicode characters, is to use -the Text::Unidecode module available from CPAN. Either use the module -explicitly: - - use Text::Soundex; - use Text::Unidecode; - - print soundex(unidecode("Fran\xE7ais")), "\n"; # Prints "F652\n" - -Or use the convenient wrapper routine: - - use Text::Soundex 'soundex_unicode'; - - print soundex_unicode("Fran\xE7ais"), "\n"; # Prints "F652\n" - -Since the soundex algorithm maps a large space (strings of arbitrary -length) onto a small space (single letter plus 3 digits) no inference -can be made about the similarity of two strings which end up with the -same soundex code. For example, both C<Hilbert> and C<Heilbronn> end -up with a soundex code of C<H416>. - -=head1 MAINTAINER - -This module is currently maintain by Mark Mielke (C<mark@mielke.cc>). - -=head1 HISTORY - -Version 3 is a significant update to provide support for versions of -Perl later than Perl 5.004. Specifically, the XS version of the -soundex() subroutine understands strings that are encoded using UTF-8 -(unicode strings). - -Version 2 of this module was a re-write by Mark Mielke (C<mark@mielke.cc>) -to improve the speed of the subroutines. The XS version of the soundex() -subroutine was introduced in 2.00. - -Version 1 of this module was written by Mike Stok (C<mike@stok.co.uk>) -and was included into the Perl core library set. - -Dave Carlsen (C<dcarlsen@csranet.com>) made the request for the NARA -algorithm to be included. The NARA soundex page can be viewed at: -C<http://www.nara.gov/genealogy/soundex/soundex.html> - -Ian Phillips (C<ian@pipex.net>) and Rich Pinder (C<rpinder@hsc.usc.edu>) -supplied ideas and spotted mistakes for v1.x. - -=cut diff --git a/Master/tlpkg/tlperl/lib/Text/Tabs.pm b/Master/tlpkg/tlperl/lib/Text/Tabs.pm deleted file mode 100755 index d3c06a08c10..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Tabs.pm +++ /dev/null @@ -1,136 +0,0 @@ - -package Text::Tabs; - -require Exporter; - -@ISA = (Exporter); -@EXPORT = qw(expand unexpand $tabstop); - -use vars qw($VERSION $tabstop $debug); -$VERSION = 2009.0305; - -use strict; - -BEGIN { - $tabstop = 8; - $debug = 0; -} - -sub expand { - my @l; - my $pad; - for ( @_ ) { - my $s = ''; - for (split(/^/m, $_, -1)) { - my $offs = 0; - s{\t}{ - $pad = $tabstop - (pos() + $offs) % $tabstop; - $offs += $pad - 1; - " " x $pad; - }eg; - $s .= $_; - } - push(@l, $s); - } - return @l if wantarray; - return $l[0]; -} - -sub unexpand -{ - my (@l) = @_; - my @e; - my $x; - my $line; - my @lines; - my $lastbit; - my $ts_as_space = " "x$tabstop; - for $x (@l) { - @lines = split("\n", $x, -1); - for $line (@lines) { - $line = expand($line); - @e = split(/(.{$tabstop})/,$line,-1); - $lastbit = pop(@e); - $lastbit = '' - unless defined $lastbit; - $lastbit = "\t" - if $lastbit eq $ts_as_space; - for $_ (@e) { - if ($debug) { - my $x = $_; - $x =~ s/\t/^I\t/gs; - print "sub on '$x'\n"; - } - s/ +$/\t/; - } - $line = join('',@e, $lastbit); - } - $x = join("\n", @lines); - } - return @l if wantarray; - return $l[0]; -} - -1; -__END__ - -sub expand -{ - my (@l) = @_; - for $_ (@l) { - 1 while s/(^|\n)([^\t\n]*)(\t+)/ - $1. $2 . (" " x - ($tabstop * length($3) - - (length($2) % $tabstop))) - /sex; - } - return @l if wantarray; - return $l[0]; -} - - -=head1 NAME - -Text::Tabs -- expand and unexpand tabs per the unix expand(1) and unexpand(1) - -=head1 SYNOPSIS - - use Text::Tabs; - - $tabstop = 4; # default = 8 - @lines_without_tabs = expand(@lines_with_tabs); - @lines_with_tabs = unexpand(@lines_without_tabs); - -=head1 DESCRIPTION - -Text::Tabs does about what the unix utilities expand(1) and unexpand(1) -do. Given a line with tabs in it, expand will replace the tabs with -the appropriate number of spaces. Given a line with or without tabs in -it, unexpand will add tabs when it can save bytes by doing so (just -like C<unexpand -a>). Invisible compression with plain ASCII! - -=head1 EXAMPLE - - #!perl - # unexpand -a - use Text::Tabs; - - while (<>) { - print unexpand $_; - } - -Instead of the C<expand> comand, use: - - perl -MText::Tabs -n -e 'print expand $_' - -Instead of the C<unexpand -a> command, use: - - perl -MText::Tabs -n -e 'print unexpand $_' - -=head1 LICENSE - -Copyright (C) 1996-2002,2005,2006 David Muir Sharnoff. -Copyright (C) 2005 Aristotle Pagaltzis -This module may be modified, used, copied, and redistributed at your own risk. -Publicly redistributed modified versions must use a different name. - diff --git a/Master/tlpkg/tlperl/lib/Text/Wrap.pm b/Master/tlpkg/tlperl/lib/Text/Wrap.pm deleted file mode 100755 index de8620247f2..00000000000 --- a/Master/tlpkg/tlperl/lib/Text/Wrap.pm +++ /dev/null @@ -1,265 +0,0 @@ -package Text::Wrap; - -use warnings::register; -require Exporter; - -@ISA = qw(Exporter); -@EXPORT = qw(wrap fill); -@EXPORT_OK = qw($columns $break $huge); - -$VERSION = 2009.0305; - -use vars qw($VERSION $columns $debug $break $huge $unexpand $tabstop - $separator $separator2); -use strict; - -BEGIN { - $columns = 76; # <= screen width - $debug = 0; - $break = '\s'; - $huge = 'wrap'; # alternatively: 'die' or 'overflow' - $unexpand = 1; - $tabstop = 8; - $separator = "\n"; - $separator2 = undef; -} - -use Text::Tabs qw(expand unexpand); - -sub wrap -{ - my ($ip, $xp, @t) = @_; - - local($Text::Tabs::tabstop) = $tabstop; - my $r = ""; - my $tail = pop(@t); - my $t = expand(join("", (map { /\s+\z/ ? ( $_ ) : ($_, ' ') } @t), $tail)); - my $lead = $ip; - my $nll = $columns - length(expand($xp)) - 1; - if ($nll <= 0 && $xp ne '') { - my $nc = length(expand($xp)) + 2; - warnings::warnif "Increasing \$Text::Wrap::columns from $columns to $nc to accommodate length of subsequent tab"; - $columns = $nc; - $nll = 1; - } - my $ll = $columns - length(expand($ip)) - 1; - $ll = 0 if $ll < 0; - my $nl = ""; - my $remainder = ""; - - use re 'taint'; - - pos($t) = 0; - while ($t !~ /\G(?:$break)*\Z/gc) { - if ($t =~ /\G([^\n]{0,$ll})($break|\n+|\z)/xmgc) { - $r .= $unexpand - ? unexpand($nl . $lead . $1) - : $nl . $lead . $1; - $remainder = $2; - } elsif ($huge eq 'wrap' && $t =~ /\G([^\n]{$ll})/gc) { - $r .= $unexpand - ? unexpand($nl . $lead . $1) - : $nl . $lead . $1; - $remainder = defined($separator2) ? $separator2 : $separator; - } elsif ($huge eq 'overflow' && $t =~ /\G([^\n]*?)($break|\n+|\z)/xmgc) { - $r .= $unexpand - ? unexpand($nl . $lead . $1) - : $nl . $lead . $1; - $remainder = $2; - } elsif ($huge eq 'die') { - die "couldn't wrap '$t'"; - } elsif ($columns < 2) { - warnings::warnif "Increasing \$Text::Wrap::columns from $columns to 2"; - $columns = 2; - return ($ip, $xp, @t); - } else { - die "This shouldn't happen"; - } - - $lead = $xp; - $ll = $nll; - $nl = defined($separator2) - ? ($remainder eq "\n" - ? "\n" - : $separator2) - : $separator; - } - $r .= $remainder; - - print "-----------$r---------\n" if $debug; - - print "Finish up with '$lead'\n" if $debug; - - $r .= $lead . substr($t, pos($t), length($t)-pos($t)) - if pos($t) ne length($t); - - print "-----------$r---------\n" if $debug;; - - return $r; -} - -sub fill -{ - my ($ip, $xp, @raw) = @_; - my @para; - my $pp; - - for $pp (split(/\n\s+/, join("\n",@raw))) { - $pp =~ s/\s+/ /g; - my $x = wrap($ip, $xp, $pp); - push(@para, $x); - } - - # if paragraph_indent is the same as line_indent, - # separate paragraphs with blank lines - - my $ps = ($ip eq $xp) ? "\n\n" : "\n"; - return join ($ps, @para); -} - -1; -__END__ - -=head1 NAME - -Text::Wrap - line wrapping to form simple paragraphs - -=head1 SYNOPSIS - -B<Example 1> - - use Text::Wrap; - - $initial_tab = "\t"; # Tab before first line - $subsequent_tab = ""; # All other lines flush left - - print wrap($initial_tab, $subsequent_tab, @text); - print fill($initial_tab, $subsequent_tab, @text); - - $lines = wrap($initial_tab, $subsequent_tab, @text); - - @paragraphs = fill($initial_tab, $subsequent_tab, @text); - -B<Example 2> - - use Text::Wrap qw(wrap $columns $huge); - - $columns = 132; # Wrap at 132 characters - $huge = 'die'; - $huge = 'wrap'; - $huge = 'overflow'; - -B<Example 3> - - use Text::Wrap; - - $Text::Wrap::columns = 72; - print wrap('', '', @text); - -=head1 DESCRIPTION - -C<Text::Wrap::wrap()> is a very simple paragraph formatter. It formats a -single paragraph at a time by breaking lines at word boundaries. -Indentation is controlled for the first line (C<$initial_tab>) and -all subsequent lines (C<$subsequent_tab>) independently. Please note: -C<$initial_tab> and C<$subsequent_tab> are the literal strings that will -be used: it is unlikely you would want to pass in a number. - -Text::Wrap::fill() is a simple multi-paragraph formatter. It formats -each paragraph separately and then joins them together when it's done. It -will destroy any whitespace in the original text. It breaks text into -paragraphs by looking for whitespace after a newline. In other respects -it acts like wrap(). - -Both C<wrap()> and C<fill()> return a single string. - -=head1 OVERRIDES - -C<Text::Wrap::wrap()> has a number of variables that control its behavior. -Because other modules might be using C<Text::Wrap::wrap()> it is suggested -that you leave these variables alone! If you can't do that, then -use C<local($Text::Wrap::VARIABLE) = YOURVALUE> when you change the -values so that the original value is restored. This C<local()> trick -will not work if you import the variable into your own namespace. - -Lines are wrapped at C<$Text::Wrap::columns> columns (default value: 76). -C<$Text::Wrap::columns> should be set to the full width of your output -device. In fact, every resulting line will have length of no more than -C<$columns - 1>. - -It is possible to control which characters terminate words by -modifying C<$Text::Wrap::break>. Set this to a string such as -C<'[\s:]'> (to break before spaces or colons) or a pre-compiled regexp -such as C<qr/[\s']/> (to break before spaces or apostrophes). The -default is simply C<'\s'>; that is, words are terminated by spaces. -(This means, among other things, that trailing punctuation such as -full stops or commas stay with the word they are "attached" to.) -Setting C<$Text::Wrap::break> to a regular expression that doesn't -eat any characters (perhaps just a forward look-ahead assertion) will -cause warnings. - -Beginner note: In example 2, above C<$columns> is imported into -the local namespace, and set locally. In example 3, -C<$Text::Wrap::columns> is set in its own namespace without importing it. - -C<Text::Wrap::wrap()> starts its work by expanding all the tabs in its -input into spaces. The last thing it does it to turn spaces back -into tabs. If you do not want tabs in your results, set -C<$Text::Wrap::unexpand> to a false value. Likewise if you do not -want to use 8-character tabstops, set C<$Text::Wrap::tabstop> to -the number of characters you do want for your tabstops. - -If you want to separate your lines with something other than C<\n> -then set C<$Text::Wrap::separator> to your preference. This replaces -all newlines with C<$Text::Wrap::separator>. If you just want to -preserve existing newlines but add new breaks with something else, set -C<$Text::Wrap::separator2> instead. - -When words that are longer than C<$columns> are encountered, they -are broken up. C<wrap()> adds a C<"\n"> at column C<$columns>. -This behavior can be overridden by setting C<$huge> to -'die' or to 'overflow'. When set to 'die', large words will cause -C<die()> to be called. When set to 'overflow', large words will be -left intact. - -Historical notes: 'die' used to be the default value of -C<$huge>. Now, 'wrap' is the default value. - -=head1 EXAMPLES - -Code: - - print wrap("\t","",<<END); - This is a bit of text that forms - a normal book-style indented paragraph - END - -Result: - - " This is a bit of text that forms - a normal book-style indented paragraph - " - -Code: - - $Text::Wrap::columns=20; - $Text::Wrap::separator="|"; - print wrap("","","This is a bit of text that forms a normal book-style paragraph"); - -Result: - - "This is a bit of|text that forms a|normal book-style|paragraph" - -=head1 SEE ALSO - -For wrapping multi-byte characters: L<Text::WrapI18N>. -For more detailed controls: L<Text::Format>. - -=head1 LICENSE - -David Muir Sharnoff <muir@idiom.org> with help from Tim Pierce and -many many others. Copyright (C) 1996-2009 David Muir Sharnoff. -This module may be modified, used, copied, and redistributed at -your own risk. Publicly redistributed versions that are modified -must use a different name. - |