【问题标题】:How to read multiple files from a directory, extract specific strings and ouput to an html file?如何从目录中读取多个文件,提取特定字符串并输出到 html 文件?
【发布时间】:2011-04-11 23:35:44
【问题描述】:

你好,

我有以下代码,我一直在想如何继续修改它,所以它会询问目录,读取目录中的所有文件,然后提取特定字符串并输出到 html 文件?提前致谢。


#!/usr/local/bin/perl

use warnings;
use strict;
use Cwd;


print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;      


open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";


# Evaluates the file and imports it into an array.
my @comment_array = ;
close(INPUT_FILE);
chomp @comment_array;
@comment_array = grep /^\s*#/g, @comment_array;

my $comment;

foreach $comment (@comment_array) {
        $comment =~ /####/; #Pattern match to grab only #s


# Prints comments to screen
Print results in html format

# Writes comments to output.html
Writes results to html file


}

close (OUTPUT);

【问题讨论】:

    标签: perl pattern-matching


    【解决方案1】:

    一步一个脚印。您有很多计划,但到目前为止,您甚至还没有更改提示字符串来请求目录。

    要读取输入的目录名称,您的:

    my $perlfile =STDIN;
    

    给出一个错误(在use strict; 下)。首先查找该错误(use diagnostics; 自动执行此操作)并尝试找出您应该做什么。

    一旦您可以提示输入目录名称并将其打印出来,然后添加代码以打开目录并读取目录。可以使用opendirreaddir 打开和读取目​​录。在继续下一步之前,请确保您可以读取目录并打印出文件名。

    【讨论】:

      【解决方案2】:

      了解特定功能的良好起点(从 cmd 行)

      perldoc -f opendir 
      

      但是,您的特定问题的回答如下,您也可以使用命令行程序并将它们通过管道传输到字符串中以简化文件处理('cat')和模式匹配('grep')。

      #!/usr/bin/perl -w
      use strict;
      my $dir = "/tmp";
      my $dh;
      my @patterns;
      my $file;
      
      opendir($dh,$dir);
      while ($file = readdir($dh)){
          if (-f "$dir/$file"){
              my $string = `cat $dir/$file | grep pattern123`;
              push @patterns, $string;
          }
      }
      closedir($dh);
      
      my $html = join("<br>",@patterns);
      open F, ">out.html";
      print F $html;
      close F;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        • 1970-01-01
        • 2016-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-18
        相关资源
        最近更新 更多