如何从目录读取多个文件,提取特定字符串并输出到 html 文件?
您好,
我有以下代码,但我不知道如何继续修改它,以便它会询问目录,读取目录中的所有文件,然后提取特定字符串并输出到 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);
Greetings,
I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.
#!/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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一步一步地进行。您已经计划了很多,但到目前为止您甚至还没有更改提示字符串来请求目录。
要读取输入的目录名称,您的:
会给出错误(在
use strict;
下)。首先查找错误(使用诊断;
自动执行此操作)并尝试找出您应该做什么。一旦可以提示输入目录名称并将其打印出来,然后添加代码以打开该目录并读取该目录。可以使用
opendir
和readdir
打开和读取目录。确保您可以读取目录并打印出文件名,然后再继续下一步。Take it one step at a time. You have a lot planned, but so far you haven't even changed your prompt string to ask for a directory.
To read the entered directory name, your:
gives an error (under
use strict;
). Start by looking that error up (use diagnostics;
automates this) and trying to figure out what you should be doing instead.Once you can prompt for a directory name and print it out, then add code to open the directory and read the directory. Directories can be opened and read with
opendir
andreaddir
. Make sure you can read the directory and print out the filenames before going on to the next step.学习特定函数(从命令行)的一个很好的起点
但是,您的特定问题的答案如下,您还可以使用命令行程序并将它们传输到字符串中以简化文件处理('cat')和模式匹配('grep')。
a good starting point to learn about specific functions (from the cmd line)
However, your particular problem is answered as follows, you can also use command line programs and pipe them into a string to simplify file handling ('cat') and pattern matching ('grep').