【发布时间】:2015-07-19 19:23:28
【问题描述】:
我对 perl 很陌生,需要一些帮助,基本上我想要的是一个程序,它可以从文件夹中读取所有 .txt 文件,执行脚本并将输出放入具有新名称的新文件夹中。当我当时处理一个文件并指定文件名时,一切正常。但我无法让它处理文件夹中的所有文件。这就是我已经走了多远。
#!/usr/bin/perl
use warnings;
use strict;
use Path::Class;
use autodie;
use File::Find;
my @now = localtime();
my $timeStamp = sprintf(
"%04d%02d%02d-%02d:%02d:%02d",
$now[5] + 1900,
$now[4] + 1,
$now[3], $now[2], $now[1], $now[0]); #A function that translates time
my %wordcount;
my $dir = "/home/smenk/.filfolder";
opendir(DIR, $dir) || die "Kan inte öppna $dir: $!";
my @files = grep { /txt/ } readdir(DIR);
closedir DIR;
my $new_dir = dir("/home/smenk/.result"); # Reads in the folder for save
my $new_file = $new_dir->file("$timeStamp.log"); # Reads in the new file timestamp variable
open my $fh, '<', $dir or die "Kunde inte öppna '$dir' $!";
open my $fhn, '>', $new_file or die "test '$new_file'";
foreach my $file (@files) {
open(FH, "/home/smenk/.filfolder/$file") || die "Unable to open $file - $!\n";
while (<FH>) {
}
close(FH);
}
while (my $line = <$fh>) {
foreach my $str (split /\s+/, $line) {
$wordcount{$str}++;
}
}
my @listing = (sort { $wordcount{$b} <=> $wordcount{$a} } keys %wordcount)[0 .. 9];
foreach my $str (@listing) {
my $output = $wordcount{$str} . " $str\n";
print $fhn $output;
}
【问题讨论】:
-
也许你有一个错字:
open (FH, "/home/smenk/.filfolde/$file")。.filfolde应该是.filfolder,不是吗? -
已修复,谢谢,仍然得到空文件
-
你在这里混合了这么多不同的东西。例如,如果要使用
Path::Class::dir,则不需要opendir/readdir。 -
好吧,你从来没有给
$fhn写过任何东西,所以它正在创建没有内容的文件。 -
和
$fh正在打开一个目录,就好像它是一个文件一样,它不能做任何有用的事情。它不会引起问题的唯一原因是你也从不使用那个。
标签: perl