MAN page from openSUSE Leap 15 perl-Pod-Parser-1.63-lp150.1.2.noarch.rpm
Pod::Parser
Section: User Contributed Perl Documentation (3)
Updated: 2016-03-08
Index NAME
Pod::Parser - base class for creating POD filters and translators
SYNOPSIS
use Pod::Parser; package MyParser; @ISA = qw(Pod::Parser); sub command { my ($parser, $command, $paragraph, $line_num) = @_; ## Interpret the command and its text; sample actions might be: if ($command eq 'head1') { ... } elsif ($command eq 'head2') { ... } ## ... other commands and their actions my $out_fh = $parser->output_handle(); my $expansion = $parser->interpolate($paragraph, $line_num); print $out_fh $expansion; } sub verbatim { my ($parser, $paragraph, $line_num) = @_; ## Format verbatim paragraph; sample actions might be: my $out_fh = $parser->output_handle(); print $out_fh $paragraph; } sub textblock { my ($parser, $paragraph, $line_num) = @_; ## Translate/Format this block of text; sample actions might be: my $out_fh = $parser->output_handle(); my $expansion = $parser->interpolate($paragraph, $line_num); print $out_fh $expansion; } sub interior_sequence { my ($parser, $seq_command, $seq_argument) = @_; ## Expand an interior sequence; sample actions might be: return "*$seq_argument*" if ($seq_command eq 'B'); return "`$seq_argument'" if ($seq_command eq 'C'); return "_${seq_argument}_'" if ($seq_command eq 'I'); ## ... other sequence commands and their resulting text } package main; ## Create a parser object and have it parse file whose name was ## given on the command-line (use STDIN if no files were given). $parser = new MyParser(); $parser->parse_from_filehandle(\*STDIN) if (@ARGV == 0); for (@ARGV) { $parser->parse_from_file($_); }
REQUIRES
perl5.005, Pod::InputObjects, Exporter, Symbol, Carp
EXPORTS
Nothing.
DESCRIPTION
NOTE: This module is considered legacy; modern Perl releases (5.18 andhigher) are going to remove Pod-Parser from core and use Pod-Simplefor all things POD.Pod::Parser is a base class for creating POD filters and translators.It handles most of the effort involved with parsing the POD sectionsfrom an input stream, leaving subclasses free to be concerned only withperforming the actual translation of text.
Pod::Parser parses PODs, and makes method calls to handle the variouscomponents of the POD. Subclasses of Pod::Parser override these methodsto translate the POD into whatever output format they desire.
QUICK OVERVIEW
To create a
POD filter for translating
POD documentation into some otherformat, you create a subclass of
Pod::Parser which typically overridesjust the base class implementation for the following methods:
- *
- command()
- *
- verbatim()
- *
- textblock()
- *
- interior_sequence()
You may also want to override the begin_input() and end_input()methods for your subclass (to perform any needed per-file and/orper-document initialization or cleanup).
If you need to perform any preprocessing of input before it is parsedyou may want to override one or more of preprocess_line() and/orpreprocess_paragraph().
Sometimes it may be necessary to make more than one pass over the inputfiles. If this is the case you have several options. You can make thefirst pass using Pod::Parser and override your methods to store theintermediate results in memory somewhere for the end_pod() method toprocess. You could use Pod::Parser for several passes with anappropriate state variable to control the operation for each pass. Ifyour input source can't be reset to start at the beginning, you canstore it in some other structure as a string or an array and have thatstructure implement a getline() method (which is all thatparse_from_filehandle() uses to read input).
Feel free to add any member data fields you need to keep track of thingslike current font, indentation, horizontal or vertical position, orwhatever else you like. Be sure to read ``PRIVATE METHODS AND DATA''to avoid name collisions.
For the most part, the Pod::Parser base class should be able todo most of the input parsing for you and leave you free to worry abouthow to interpret the commands and translate the result.
Note that all we have described here in this quick overview is thesimplest most straightforward use of Pod::Parser to do stream-basedparsing. It is also possible to use the Pod::Parser::parse_text functionto do more sophisticated tree-based parsing. See ``TREE-BASED PARSING''.
PARSING OPTIONS
A
parse-option is simply a named option of
Pod::Parser with avalue that corresponds to a certain specified behavior. These variousbehaviors of
Pod::Parser may be enabled/disabled by settingor unsetting one or more
parse-options using the
parseopts()
method.The set of currently accepted parse-options is as follows:
- -want_nonPODs (default: unset)
- Normally (by default) Pod::Parser will only provide access tothe POD sections of the input. Input paragraphs that are not partof the POD-format documentation are not made available to the caller(not even using preprocess_paragraph()). Setting this option to anon-empty, non-zero value will allow preprocess_paragraph() to seenon-POD sections of the input as well as POD sections. The cutting()method can be used to determine if the corresponding paragraph is a PODparagraph, or some other input paragraph.
- -process_cut_cmd (default: unset)
- Normally (by default) Pod::Parser handles the "=cut" POD directiveby itself and does not pass it on to the caller for processing. Settingthis option to a non-empty, non-zero value will cause Pod::Parser topass the "=cut" directive to the caller just like any other POD command(and hence it may be processed by the command() method).
Pod::Parser will still interpret the "=cut" directive to mean that``cutting mode'' has been (re)entered, but the caller will get a chanceto capture the actual "=cut" paragraph itself for whatever purposeit desires.
- -warnings (default: unset)
- Normally (by default) Pod::Parser recognizes a bare minimum ofpod syntax errors and warnings and issues diagnostic messagesfor errors, but not for warnings. (Use Pod::Checker to do morethorough checking of POD syntax.) Setting this option to a non-empty,non-zero value will cause Pod::Parser to issue diagnostics forthe few warnings it recognizes as well as the errors.
Please see ``parseopts()'' for a complete description of the interfacefor the setting and unsetting of parse-options.
RECOMMENDED SUBROUTINE/METHOD OVERRIDES
Pod::Parser provides several methods which most subclasses will probablywant to override. These methods are as follows:
command()
$parser->command($cmd,$text,$line_num,$pod_para);
This method should be overridden by subclasses to take the appropriateaction when a POD command paragraph (denoted by a line beginning with``='') is encountered. When such a POD directive is seen in the input,this method is called and is passed:
- $cmd
- the name of the command for this POD paragraph
- $text
- the paragraph text for the given POD paragraph command.
- $line_num
- the line-number of the beginning of the paragraph
- $pod_para
- a reference to a "Pod::Paragraph" object which contains furtherinformation about the paragraph command (see Pod::InputObjectsfor details).
Note that this method is called for "=pod" paragraphs.
The base class implementation of this method simply treats the raw PODcommand as normal block of paragraph text (invoking the textblock()method with the command paragraph).
verbatim()
$parser->verbatim($text,$line_num,$pod_para);
This method may be overridden by subclasses to take the appropriateaction when a block of verbatim text is encountered. It is passed thefollowing parameters:
- $text
- the block of text for the verbatim paragraph
- $line_num
- the line-number of the beginning of the paragraph
- $pod_para
- a reference to a "Pod::Paragraph" object which contains furtherinformation about the paragraph (see Pod::InputObjectsfor details).
The base class implementation of this method simply prints the textblock(unmodified) to the output filehandle.
textblock()
$parser->textblock($text,$line_num,$pod_para);
This method may be overridden by subclasses to take the appropriateaction when a normal block of POD text is encountered (although the baseclass method will usually do what you want). It is passed the followingparameters:
- $text
- the block of text for the a POD paragraph
- $line_num
- the line-number of the beginning of the paragraph
- $pod_para
- a reference to a "Pod::Paragraph" object which contains furtherinformation about the paragraph (see Pod::InputObjectsfor details).
In order to process interior sequences, subclasses implementations ofthis method will probably want to invoke either interpolate() orparse_text(), passing it the text block $text, and the correspondingline number in $line_num, and then perform any desired processing uponthe returned result.
The base class implementation of this method simply prints the text blockas it occurred in the input stream).
interior_sequence()
$parser->interior_sequence($seq_cmd,$seq_arg,$pod_seq);
This method should be overridden by subclasses to take the appropriateaction when an interior sequence is encountered. An interior sequence isan embedded command within a block of text which appears as a commandname (usually a single uppercase character) followed immediately by astring of text which is enclosed in angle brackets. This method ispassed the sequence command $seq_cmd and the corresponding text$seq_arg. It is invoked by the interpolate() method for each interiorsequence that occurs in the string that it is passed. It should returnthe desired text string to be used in place of the interior sequence.The $pod_seq argument is a reference to a "Pod::InteriorSequence"object which contains further information about the interior sequence.Please see Pod::InputObjects for details if you need to access thisadditional information.
Subclass implementations of this method may wish to invoke the nested() method of $pod_seq to see if it is nested insidesome other interior-sequence (and if so, which kind).
The base class implementation of the interior_sequence() methodsimply returns the raw text of the interior sequence (as it occurredin the input) to the caller.
OPTIONAL SUBROUTINE/METHOD OVERRIDES
Pod::Parser provides several methods which subclasses may want to overrideto perform any special pre/post-processing. These methods do
not have tobe overridden, but it may be useful for subclasses to take advantage of them.
new()
my $parser = Pod::Parser->new();
This is the constructor for Pod::Parser and its subclasses. Youdo not need to override this method! It is capable of constructingsubclass objects as well as base class objects, provided you useany of the following constructor invocation styles:
my $parser1 = MyParser->new(); my $parser2 = new MyParser(); my $parser3 = $parser2->new();
where "MyParser" is some subclass of Pod::Parser.
Using the syntax "MyParser::new()" to invoke the constructor is notrecommended, but if you insist on being able to do this, then thesubclass will need to override the new() constructor method. Ifyou do override the constructor, you must be sure to invoke theinitialize() method of the newly blessed object.
Using any of the above invocations, the first argument to theconstructor is always the corresponding package name (or objectreference). No other arguments are required, but if desired, anassociative array (or hash-table) my be passed to the new()constructor, as in:
my $parser1 = MyParser->new( MYDATA => $value1, MOREDATA => $value2 ); my $parser2 = new MyParser( -myflag => 1 );
All arguments passed to the new() constructor will be treated askey/value pairs in a hash-table. The newly constructed object will beinitialized by copying the contents of the given hash-table (which mayhave been empty). The new() constructor for this class and all of itssubclasses returns a blessed reference to the initialized object (hash-table).
initialize()
$parser->initialize();
This method performs any necessary object initialization. It takes noarguments (other than the object instance of course, which is typicallycopied to a local variable named $self). If subclasses override thismethod then they must be sure to invoke "$self->SUPER::initialize()".
begin_pod()
$parser->begin_pod();
This method is invoked at the beginning of processing for each PODdocument that is encountered in the input. Subclasses should overridethis method to perform any per-document initialization.
begin_input()
$parser->begin_input();
This method is invoked by parse_from_filehandle() immediately beforeprocessing input from a filehandle. The base class implementation doesnothing, however, subclasses may override it to perform any per-fileinitializations.
Note that if multiple files are parsed for a single POD document(perhaps the result of some future "=include" directive) this methodis invoked for every file that is parsed. If you wish to perform certaininitializations once per document, then you should use begin_pod().
end_input()
$parser->end_input();
This method is invoked by parse_from_filehandle() immediately afterprocessing input from a filehandle. The base class implementation doesnothing, however, subclasses may override it to perform any per-filecleanup actions.
Please note that if multiple files are parsed for a single POD document(perhaps the result of some kind of "=include" directive) this methodis invoked for every file that is parsed. If you wish to perform certaincleanup actions once per document, then you should use end_pod().
end_pod()
$parser->end_pod();
This method is invoked at the end of processing for each POD documentthat is encountered in the input. Subclasses should override this methodto perform any per-document finalization.
preprocess_line()
$textline = $parser->preprocess_line($text, $line_num);
This method should be overridden by subclasses that wish to performany kind of preprocessing for each line of input (before it hasbeen determined whether or not it is part of a POD paragraph). Theparameter $text is the input line; and the parameter $line_num isthe line number of the corresponding text line.
The value returned should correspond to the new text to use in itsplace. If the empty string or an undefined value is returned then nofurther processing will be performed for this line.
Please note that the preprocess_line() method is invoked beforethe preprocess_paragraph() method. After all (possibly preprocessed)lines in a paragraph have been assembled together and it has beendetermined that the paragraph is part of the POD documentation from oneof the selected sections, then preprocess_paragraph() is invoked.
The base class implementation of this method returns the given text.
preprocess_paragraph()
$textblock = $parser->preprocess_paragraph($text, $line_num);
This method should be overridden by subclasses that wish to perform anykind of preprocessing for each block (paragraph) of POD documentationthat appears in the input stream. The parameter $text is the PODparagraph from the input file; and the parameter $line_num is theline number for the beginning of the corresponding paragraph.
The value returned should correspond to the new text to use in itsplace If the empty string is returned or an undefined value isreturned, then the given $text is ignored (not processed).
This method is invoked after gathering up all the lines in a paragraphand after determining the cutting state of the paragraph,but before trying to further parse or interpret them. Afterpreprocess_paragraph() returns, the current cutting state (whichis returned by "$self->cutting()") is examined. If it evaluatesto true then input text (including the given $text) is cut (notprocessed) until the next POD directive is encountered.
Please note that the preprocess_line() method is invoked beforethe preprocess_paragraph() method. After all (possibly preprocessed)lines in a paragraph have been assembled together and either it has beendetermined that the paragraph is part of the POD documentation from oneof the selected sections or the "-want_nonPODs" option is true,then preprocess_paragraph() is invoked.
The base class implementation of this method returns the given text.
METHODS FOR PARSING AND PROCESSING
Pod::Parser provides several methods to process input text. Thesemethods typically won't need to be overridden (and in some cases theycan't be overridden), but subclasses may want to invoke them to exploittheir functionality.
parse_text()
$ptree1 = $parser->parse_text($text, $line_num); $ptree2 = $parser->parse_text({%opts}, $text, $line_num); $ptree3 = $parser->parse_text(\%opts, $text, $line_num);
This method is useful if you need to perform your own interpolation of interior sequences and can't rely upon interpolate to expandthem in simple bottom-up order.
The parameter $text is a string or block of text to be parsedfor interior sequences; and the parameter $line_num is theline number corresponding to the beginning of $text.
parse_text() will parse the given text into a parse-tree of ``nodes.''and interior-sequences. Each ``node'' in the parse tree is either atext-string, or a Pod::InteriorSequence. The result returned is aparse-tree of type Pod::ParseTree. Please see Pod::InputObjectsfor more information about Pod::InteriorSequence and Pod::ParseTree.
If desired, an optional hash-ref may be specified as the first argumentto customize certain aspects of the parse-tree that is created andreturned. The set of recognized option keywords are:
- -expand_seq => code-ref|method-name
- Normally, the parse-tree returned by parse_text() will contain anunexpanded "Pod::InteriorSequence" object for each interior-sequenceencountered. Specifying -expand_seq tells parse_text() to ``expand''every interior-sequence it sees by invoking the referenced function(or named method of the parser object) and using the return value as theexpanded result.
If a subroutine reference was given, it is invoked as:
&$code_ref( $parser, $sequence )
and if a method-name was given, it is invoked as:
$parser->method_name( $sequence )
where $parser is a reference to the parser object, and $sequenceis a reference to the interior-sequence object.[NOTE: If the interior_sequence() method is specified, then it isinvoked according to the interface specified in ``interior_sequence()''].
- -expand_text => code-ref|method-name
- Normally, the parse-tree returned by parse_text() will contain atext-string for each contiguous sequence of characters outside of aninterior-sequence. Specifying -expand_text tells parse_text() to``preprocess'' every such text-string it sees by invoking the referencedfunction (or named method of the parser object) and using the return valueas the preprocessed (or ``expanded'') result. [Note that if the result isan interior-sequence, then it will not be expanded as specified by the-expand_seq option; Any such recursive expansion needs to be handled bythe specified callback routine.]
If a subroutine reference was given, it is invoked as:
&$code_ref( $parser, $text, $ptree_node )
and if a method-name was given, it is invoked as:
$parser->method_name( $text, $ptree_node )
where $parser is a reference to the parser object, $text is thetext-string encountered, and $ptree_node is a reference to the currentnode in the parse-tree (usually an interior-sequence object or else thetop-level node of the parse-tree).
- -expand_ptree => code-ref|method-name
- Rather than returning a "Pod::ParseTree", pass the parse-tree as anargument to the referenced subroutine (or named method of the parserobject) and return the result instead of the parse-tree object.
If a subroutine reference was given, it is invoked as:
&$code_ref( $parser, $ptree )
and if a method-name was given, it is invoked as:
$parser->method_name( $ptree )
where $parser is a reference to the parser object, and $ptreeis a reference to the parse-tree object.
interpolate()
$textblock = $parser->interpolate($text, $line_num);
This method translates all text (including any embedded interior sequences)in the given text string $text and returns the interpolated result. Theparameter $line_num is the line number corresponding to the beginningof $text.
interpolate() merely invokes a private method to recursively expandnested interior sequences in bottom-up order (innermost sequences areexpanded first). If there is a need to expand nested sequences insome alternate order, use parse_text instead.
parse_from_filehandle()
$parser->parse_from_filehandle($in_fh,$out_fh);
This method takes an input filehandle (which is assumed to already beopened for reading) and reads the entire input stream looking for blocks(paragraphs) of POD documentation to be processed. If no first argumentis given the default input filehandle "STDIN" is used.
The $in_fh parameter may be any object that provides a getline()method to retrieve a single line of input text (hence, an appropriatewrapper object could be used to parse PODs from a single string or anarray of strings).
Using "$in_fh->getline()", input is read line-by-line and assembledinto paragraphs or ``blocks'' (which are separated by lines containingnothing but whitespace). For each block of POD documentationencountered it will invoke a method to parse the given paragraph.
If a second argument is given then it should correspond to a filehandle whereoutput should be sent (otherwise the default output filehandle is"STDOUT" if no output filehandle is currently in use).
NOTE: For performance reasons, this method caches the input stream atthe top of the stack in a local variable. Any attempts by clients tochange the stack contents during processing when in the midst executingof this method will not affect the input stream used by the currentinvocation of this method.
This method does not usually need to be overridden by subclasses.
parse_from_file()
$parser->parse_from_file($filename,$outfile);
This method takes a filename and does the following:
- *
- opens the input and output files for reading(creating the appropriate filehandles)
- *
- invokes the parse_from_filehandle() method passing it thecorresponding input and output filehandles.
- *
- closes the input and output files.
If the special input filename "``, ''-`` or ''<&STDIN`` is given then the STDINfilehandle is used for input (and no open or close is performed). If noinput filename is specified then ''-" is implied. Filehandle references,or objects that support the regular IO operations (like "<$fh>"or "$fh-<Egt"getline>) are also accepted; the handles must already be opened.
If a second argument is given then it should be the name of the desiredoutput file. If the special output filename ``-'' or ``>&STDOUT'' is giventhen the STDOUT filehandle is used for output (and no open or close isperformed). If the special output filename ``>&STDERR'' is given then theSTDERR filehandle is used for output (and no open or close isperformed). If no output filehandle is currently in use and no outputfilename is specified, then ``-'' is implied.Alternatively, filehandle references or objects that support the regularIO operations (like "print", e.g. IO::String) are also accepted;the object must already be opened.
This method does not usually need to be overridden by subclasses.
ACCESSOR METHODS
Clients of
Pod::Parser should use the following methods to accessinstance data fields:
errorsub()
$parser->errorsub("method_name"); $parser->errorsub(\&warn_user); $parser->errorsub(sub { print STDERR, @_ });
Specifies the method or subroutine to use when printing error messagesabout POD syntax. The supplied method/subroutine must return TRUE uponsuccessful printing of the message. If "undef" is given, then the carpbuiltin is used to issue error messages (this is the default behavior).
my $errorsub = $parser->errorsub() my $errmsg = "This is an error message!\n" (ref $errorsub) and &{$errorsub}($errmsg) or (defined $errorsub) and $parser->$errorsub($errmsg) or carp($errmsg);
Returns a method name, or else a reference to the user-supplied subroutineused to print error messages. Returns "undef" if the carp builtinis used to issue error messages (this is the default behavior).
cutting()
$boolean = $parser->cutting();
Returns the current "cutting" state: a boolean-valued scalar whichevaluates to true if text from the input file is currently being ``cut''(meaning it is not considered part of the POD document).
$parser->cutting($boolean);
Sets the current "cutting" state to the given value and returns theresult.
parseopts()
When invoked with no additional arguments,
parseopts returns a hashtableof all the current parsing options.
## See if we are parsing non-POD sections as well as POD ones my %opts = $parser->parseopts(); $opts{'-want_nonPODs}' and print "-want_nonPODs\n";
When invoked using a single string, parseopts treats the string as thename of a parse-option and returns its corresponding value if it exists(returns "undef" if it doesn't).
## Did we ask to see '=cut' paragraphs? my $want_cut = $parser->parseopts('-process_cut_cmd'); $want_cut and print "-process_cut_cmd\n";
When invoked with multiple arguments, parseopts treats them askey/value pairs and the specified parse-option names are set to thegiven values. Any unspecified parse-options are unaffected.
## Set them back to the default $parser->parseopts(-warnings => 0);
When passed a single hash-ref, parseopts uses that hash to completelyreset the existing parse-options, all previous parse-option valuesare lost.
## Reset all options to default $parser->parseopts( { } );
See ``PARSING OPTIONS'' for more information on the name and meaning of eachparse-option currently recognized.
output_file()
$fname = $parser->output_file();
Returns the name of the output file being written.
output_handle()
$fhandle = $parser->output_handle();
Returns the output filehandle object.
input_file()
$fname = $parser->input_file();
Returns the name of the input file being read.
input_handle()
$fhandle = $parser->input_handle();
Returns the current input filehandle object.
PRIVATE METHODS AND DATA
Pod::Parser makes use of several internal methods and data fieldswhich clients should not need to see or use. For the sake of avoidingname collisions for client data and methods, these methods and fieldsare briefly discussed here. Determined hackers may obtain furtherinformation about them by reading the
Pod::Parser source code.
Private data fields are stored in the hash-object whose reference isreturned by the new() constructor for this class. The names of allprivate methods and data-fields used by Pod::Parser begin with aprefix of ``_'' and match the regular expression "/^_\w+$/".
TREE-BASED PARSING
If straightforward stream-based parsing wont meet your needs (as islikely the case for tasks such as translating PODs into structuredmarkup languages like
HTML and
XML) then you may need to take thetree-based approach. Rather than doing everything in one pass andcalling the
interpolate()
method to expand sequences into text, itmay be desirable to instead create a parse-tree using the
parse_text()
method to return a tree-like structure which may contain an orderedlist of children (each of which may be a text-string, or a similartree-like structure).
Pay special attention to ``METHODS FOR PARSING AND PROCESSING'' andto the objects described in Pod::InputObjects. The former describesthe gory details and parameters for how to customize and extend theparsing behavior of Pod::Parser. Pod::InputObjects providesseveral objects that may all be used interchangeably as parse-trees. Themost obvious one is the Pod::ParseTree object. It defines the basicinterface and functionality that all things trying to be a POD parse-treeshould do. A Pod::ParseTree is defined such that each ``node'' may be atext-string, or a reference to another parse-tree. Each Pod::Paragraphobject and each Pod::InteriorSequence object also supports the basicparse-tree interface.
The parse_text() method takes a given paragraph of text, andreturns a parse-tree that contains one or more children, each of whichmay be a text-string, or an InteriorSequence object. There are alsocallback-options that may be passed to parse_text() to customizethe way it expands or transforms interior-sequences, as well as thereturned result. These callbacks can be used to create a parse-treewith custom-made objects (which may or may not support the parse-treeinterface, depending on how you choose to do it).
If you wish to turn an entire POD document into a parse-tree, that processis fairly straightforward. The parse_text() method is the key to doingthis successfully. Every paragraph-callback (i.e. the polymorphic methodsfor command(), verbatim(), and textblock() paragraphs) takesa Pod::Paragraph object as an argument. Each paragraph object has aparse_tree() method that can be used to get or set a correspondingparse-tree. So for each of those paragraph-callback methods, simply callparse_text() with the options you desire, and then use the returnedparse-tree to assign to the given paragraph object.
That gives you a parse-tree for each paragraph - so now all you need isan ordered list of paragraphs. You can maintain that yourself as a dataelement in the object/hash. The most straightforward way would be simplyto use an array-ref, with the desired set of custom ``options'' for eachinvocation of parse_text. Let's assume the desired option-set isgiven by the hash %options. Then we might do something like thefollowing:
package MyPodParserTree; @ISA = qw( Pod::Parser ); ... sub begin_pod { my $self = shift; $self->{'-paragraphs'} = []; ## initialize paragraph list } sub command { my ($parser, $command, $paragraph, $line_num, $pod_para) = @_; my $ptree = $parser->parse_text({%options}, $paragraph, ...); $pod_para->parse_tree( $ptree ); push @{ $self->{'-paragraphs'} }, $pod_para; } sub verbatim { my ($parser, $paragraph, $line_num, $pod_para) = @_; push @{ $self->{'-paragraphs'} }, $pod_para; } sub textblock { my ($parser, $paragraph, $line_num, $pod_para) = @_; my $ptree = $parser->parse_text({%options}, $paragraph, ...); $pod_para->parse_tree( $ptree ); push @{ $self->{'-paragraphs'} }, $pod_para; } ... package main; ... my $parser = new MyPodParserTree(...); $parser->parse_from_file(...); my $paragraphs_ref = $parser->{'-paragraphs'};
Of course, in this module-author's humble opinion, I'd be more inclined touse the existing Pod::ParseTree object than a simple array. That wayeverything in it, paragraphs and sequences, all respond to the same coreinterface for all parse-tree nodes. The result would look something like:
package MyPodParserTree2; ... sub begin_pod { my $self = shift; $self->{'-ptree'} = new Pod::ParseTree; ## initialize parse-tree } sub parse_tree { ## convenience method to get/set the parse-tree for the entire POD (@_ > 1) and $_[0]->{'-ptree'} = $_[1]; return $_[0]->{'-ptree'}; } sub command { my ($parser, $command, $paragraph, $line_num, $pod_para) = @_; my $ptree = $parser->parse_text({<<options>>}, $paragraph, ...); $pod_para->parse_tree( $ptree ); $parser->parse_tree()->append( $pod_para ); } sub verbatim { my ($parser, $paragraph, $line_num, $pod_para) = @_; $parser->parse_tree()->append( $pod_para ); } sub textblock { my ($parser, $paragraph, $line_num, $pod_para) = @_; my $ptree = $parser->parse_text({<<options>>}, $paragraph, ...); $pod_para->parse_tree( $ptree ); $parser->parse_tree()->append( $pod_para ); } ... package main; ... my $parser = new MyPodParserTree2(...); $parser->parse_from_file(...); my $ptree = $parser->parse_tree; ...
Now you have the entire POD document as one great big parse-tree. Youcan even use the -expand_seq option to parse_text to insertwhole different kinds of objects. Just don't expect Pod::Parserto know what to do with them after that. That will need to be in yourcode. Or, alternatively, you can insert any object you like so long asit conforms to the Pod::ParseTree interface.
One could use this to create subclasses of Pod::Paragraphs andPod::InteriorSequences for specific commands (or to create your owncustom node-types in the parse-tree) and add some kind of emit()method to each custom node/subclass object in the tree. Then all you'dneed to do is recursively walk the tree in the desired order, processingthe children (most likely from left to right) by formatting them ifthey are text-strings, or by calling their emit() method if theyare objects/references.
CAVEATS
Please note that
POD has the notion of ``paragraphs'': this is somethingstarting
after a blank (read: empty) line, with the single exceptionof the file start, which is also starting a paragraph. That means thatespecially a command (e.g.
"=head1")
must be preceded with a blankline;
"__END__" is
not a blank line.
SEE ALSO
Pod::InputObjects, Pod::Select
Pod::InputObjects defines POD input objects corresponding tocommand paragraphs, parse-trees, and interior-sequences.
Pod::Select is a subclass of Pod::Parser which provides the abilityto selectively include and/or exclude sections of a POD document from beingtranslated based upon the current heading, subheading, subsubheading, etc.
AUTHOR
Please report bugs using <
http://rt.cpan.org>.
Brad Appleton <bradappAATTenteract.com>
Based on code for Pod::Text written byTom Christiansen <tchristAATTmox.perl.com>
LICENSE
Pod-Parser is free software; you can redistribute it and/or modify itunder the terms of the Artistic License distributed with Perl version5.000 or (at your option) any later version. Please refer to theArtistic License that came with your Perl distribution for moredetails. If your version of Perl was not distributed under theterms of the Artistic License, than you may distribute PodParserunder the same terms as Perl itself.
Index
- NAME
- SYNOPSIS
- REQUIRES
- EXPORTS
- DESCRIPTION
- QUICK OVERVIEW
- PARSING OPTIONS
- RECOMMENDED SUBROUTINE/METHOD OVERRIDES
- command()
- verbatim()
- textblock()
- interior_sequence()
- OPTIONAL SUBROUTINE/METHOD OVERRIDES
- new()
- initialize()
- begin_pod()
- begin_input()
- end_input()
- end_pod()
- preprocess_line()
- preprocess_paragraph()
- METHODS FOR PARSING AND PROCESSING
- parse_text()
- interpolate()
- parse_from_filehandle()
- parse_from_file()
- ACCESSOR METHODS
- errorsub()
- cutting()
- parseopts()
- output_file()
- output_handle()
- input_file()
- input_handle()
- PRIVATE METHODS AND DATA
- TREE-BASED PARSING
- CAVEATS
- SEE ALSO
- AUTHOR
- LICENSE
This document was created byman2html,using the manual pages.