2

我正在尝试提取 Perl POD 的一部分,仅此而已。如果我运行以下命令:

use strict;
use warnings;
use Pod::Simple;
use Pod::Text;

=head1 podTest

normal pod

=cut

print "normalPod:\n";
my $writeNormalPod = Pod::Text->new();
$writeNormalPod->parse_from_file(__FILE__);

=pod

all pod

=cut

print "\nallPod:\n";
my $writePod = Pod::Text->new();
$writePod->accept_targets( ('special') );
$writePod->parse_from_file(__FILE__);

=begin special

special pod

=end special

=cut

print "\nspecialPod:\n";
my $writeSpecialPod = Pod::Text->new();
# what to have here?
$writeSpecialPod->parse_from_file(__FILE__);
# in order to print "special pod" and nothing else

然后我得到输出:

normalPod:
podTest
    normal pod

    all pod


allPod:
podTest
    normal pod

    all pod

special pod

specialPod:

我怎样才能得到special pod而没有别的?

我尝试过的事情:

  • 不接受的代码、指令和目标
  • 附加代码(以及 cut、pod 和 whiteline)处理程序
  • 网络搜索(充其量,这会显示如何使用格式名称)

有没有一种简单的方法可以只从 POD 中获取特定格式,或者我应该自己解析文件?

4

2 回答 2

3

我尝试过的事情:不接受指令

Yes 似乎Pod::Simple不支持不接受的标准指令。如果你试试:

$writePod->unaccept_directives( 'head1' );

它因错误消息而死:

But you must accept "head1" directives -- it's a builtin!

您也许可以通过子类Pod::Text覆盖其输出方法来解决限制。例如:

p.pl

BEGIN {
package My::Pod::Text;
use strict;
use warnings;
use parent qw(Pod::Text);
sub cmd_head1 {} #override this to not print head1
sub cmd_para {}  #override this to not print paragraphs

$INC{"My/Pod/Text.pm"} = 1;
}
package main;
use feature qw(say);
use strict;
use warnings;
use My::Pod::Text;

=head1 podTest

normal pod

=begin special

special pod

=end special

=cut

my $writePod = My::Pod::Text->new();
$writePod->accept_targets( ('special') );
$writePod->parse_from_file(__FILE__);

仅输出:

special pod
于 2022-03-01T06:42:38.817 回答
1

如果您可以使用 CPAN 模块,以下是如何使用Pod::POM=begin获取特殊部分的内容。该子例程查看所有节点以找到具有特殊格式的开头。它将根节点的子节点推入堆栈,从堆栈中删除最后一个节点,如果它是特殊的开始块,则将该节点推入结果数组,然后将该节点的子节点推入堆栈,然后返回弹出节点。最后它返回结果。findBeginpop

print "Pod::POM results\n";
my $parser = Pod::POM->new();
print "\$parser is $parser\n";

my $pom = $parser->parse_file(__FILE__);

#print "\$pom is \"$pom\"\n";
my (@special) = findBegin($pom);

for my $special (@special) {
    print $special->text();
}

sub findBegin {
    my ($pom) = @_;
    my @nodes = $pom->content();
    my @results;
    while (@nodes) {
        my $node = pop @nodes;
        if ($node->type() eq 'begin' && $node->format() eq 'special') {
            #print "Returning $node\n";
            push @results, $node;
        }
        my @children = $node->content();
        push @nodes, @children if scalar @children;
    }
    return @results;
}

您可以扩展 findBegin 以便您可以通过将第一行更改为对它的每次调用使用不同的findBegin条件

my ($pom, $callback) = @_;

和 if 语句:

if ($callback->($node)) {

然后将其称为:

my (@special) = findBegin($pom, sub {
    my ($node) = @_;
    return $node->type() eq 'begin' && $node->format() eq 'special';
});

将 return 语句中的条件替换为您要测试的任何条件$node

于 2022-03-04T03:51:53.923 回答