【发布时间】:2017-04-27 20:12:46
【问题描述】:
我正在尝试读取目录中的所有 txt 文件并将它们作为链接输出到单个 html 页面上。当我打开 html 页面时,txt 文件应显示为链接。当我点击链接时,txt 文件中的内容应该会在 html 页面上打开。这是我在 perl 中的代码。
my $dir = '/'; ## rem trailing slash
my $body; ## our file list
my $saveFile = '/dev/null'; ## file to save links
opendir( MYDIR, $dir ) or die 'opendir';
$body =
join( "\n", ## make it legible
map { '<a href="$_">$_</a><br>' } ## format each file
sort { $a cmp $b } ## sort them
grep { ! /^\./ } ## no .name files
grep { -T "$dir$_ } ## only text files
readdir MYDIR
);
closedir MYDIR;
## build your link page
## using $body
open( FILE, $saveFile ) or die 'open';
print FILE <<EOF;
<HTML>
<HEAD>
<TITLE>My Files</TITLE>
<BODY>
$body
</BODY>
</HTML>
EOF
close FILE;
检索文本文件的代码,我从终端执行此代码为“perl showtxtfiles.pl > somefile.html”,它检索文件夹中的所有 txt 文件并将它们显示在 html 页面上。但是,我只需要在打开 somefile.html 页面时将每个 txt 文件显示为链接。
#!/usr/bin/perl
use strict;
use warnings;
my $dir = '/home/ubuntu/uisacad5.uis.edu/~rloui2/540/project2';
opendir(DIR, $dir) or die $!;
while (my $file = readdir(DIR)) {
# We only want files
next unless (-f "$dir/$file");
# Use a regular expression to find files ending in .txt
next unless ($file =~ m/\.txt$/);
print "$file\n";
}
closedir(DIR);
exit 0;
【问题讨论】:
-
好的...有什么问题? (提示:变量不会被插入到单引号字符串中。)