我在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;
}
答案 0 :(得分:1)
以下是使用Path::Class的阅读部分最简单的骨架(另请参阅dir和file:
#!/usr/bin/perl
use warnings;
use strict;
use Path::Class;
my $src = dir("/home/smenk/.filfolder");
my @txt_files = grep /[.] txt\z/x, $src->children;
for my $txt_file ( @txt_files ) {
my $in = $txt_file->openr;
while (my $line = <$in>) {
print "OUT: $line";
}
}
答案 1 :(得分:1)
您还可以使用另一个出色的模块Path::Tiny进行目录/文件操作,使用Time::Piece进行日期/时间功能 - 例如:
#!/usr/bin/env perl
use strict;
use warnings;
use Path::Tiny;
use Time::Piece;
my @txtfiles = path("/home/smenk/.filfolder")->children(qr/\.txt\z/);
my $outdir = path("home/smenk/.result");
$outdir->mkpath; #create the dir...
my $t = localtime;
my $outfile = $outdir->child($t->strftime("%Y%m%d-%H%M%S.txt"));
$outfile->touch;
my @outdata;
for my $infile (@txtfiles) {
my @lines = $infile->lines({chomp => 1});
#do something with lines and create the output @data
push @outdata, scalar @lines;
}
$outfile->append({truncate => 1}, map { "$_\n" } @outdata); #or spew;