smenk
smenk

Reputation: 79

Read multiple files from folder in perl

I'm pretty new on perl and in need for some help, basically what I want is a program that reads all .txt files from a folder, doing the script and throw the output in a new folder with a new name. Everything works when I'm working with one file at the time, specifying the name of the file.. But I can't get it to work with all of the files in the folder. This is how far I've gotten.

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

Upvotes: 1

Views: 2392

Answers (2)

clt60
clt60

Reputation: 63892

You can also use another great module Path::Tiny, for dir/file operations and the Time::Piece for the date/time functions - like:

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

Upvotes: 1

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118118

Here is the simplest skeleton for the reading part using Path::Class (see also dir and 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";
    }
}

Upvotes: 1

Related Questions