【问题标题】:Perl - How to crawl a directory, parse every file in the directory and extract all comments to html filePerl - 如何爬取目录,解析目录中的每个文件并将所有注释提取到 html 文件
【发布时间】:2011-04-05 22:55:10
【问题描述】:

我需要一些认真的帮助,我是 perl 的新手,需要有关如何创建 perl 脚本的帮助,该脚本会提示用户输入包含 perl 文件的目录,解析该目录中的每个文件,然后从每个文件中提取所有 cmets文件到单个 html 文件。

已经执行此操作的代码示例或现有模块会很棒。

谢谢!

【问题讨论】:

  • 您希望从中提取 cmets 的所有文件是否都属于同一类型?回答这个问题的人需要知道,因为 perl、C++ 和 html 都有不同的字符序列来表示 cmets。另外,你想要 HTML 输出吗?您希望该 html 看起来像什么(表格、列表、按文件组织等)?

标签: perl


【解决方案1】:

PPI 可用于解析 Perl 代码文件。这应该让您开始在目录中获取 Perl 文件(假设它们具有 .pl 扩展名)并获取 cmets。我不确定你对 HTML 片段的意思:

use warnings;
use strict;
use PPI;

my $dir = shift;
for my $file (glob "$dir/*.pl") {
    my $doc = PPI::Document->new($file);
    for my $com (@{ $doc->find('PPI::Token::Comment') }) {
        print $com->{content};
    }
}

更新:查看HTML::Template(但可能有点矫枉过正)。

【讨论】:

  • 谢谢,我会调查的。在 html 部分,我希望将我的所有 cmets 写入 html 文件以用于文档目的,而不使用 POD。
【解决方案2】:

使用关键字“dir”进行简单的 cpan 搜索会发现大量有用的模块。我经常使用的一种是:

IO::Dir

【讨论】:

    【解决方案3】:

    如果您有选择,这里有一个 Ruby 脚本

    #!/usr/bin/env ruby 
    print "Enter directory: "
    directory=File.join(gets.chomp,"*.pl")
    directory="/home/yhlee/test/ruby/*.pl"
    c=0
    Dir[directory].each do |file|
        c+=1
        o = File.open("file_#{c}.html","w")
        File.open(file).each do |line|
            if line[/#/]
                o.write ( line.scan(/;*\s+(#.*)$/)[0].first + "\n" ) if line[/;*\s+#/]
                o.write ( line.scan(/^\s+(#.*)$/)[0].first + "\n") if line[/^\s+#/]
            end
        end
        o.close
    end
    

    【讨论】:

    • 对于像 "while (1) { # a comment" 这样的 Perl 代码行有什么作用? (我的猜测是它做错了......)
    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2011-08-04
    • 2010-12-22
    相关资源
    最近更新 更多