【问题标题】:Read multiple files from folder in perl从perl中的文件夹中读取多个文件
【发布时间】: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


【解决方案1】:

这是使用Path::Class 的阅读部分的最简单框架(另请参阅dirfile

#!/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";
    }
}

【讨论】:

  • 谢谢,我确实使用它作为框架并实现了我自己的代码(经过一些清理),它现在完全按照我的意愿工作!
  • dirfile 的死链接
【解决方案2】:

您还可以使用另一个出色的模块 Path::Tiny,用于 dir/file 操作和 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多