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; }
open (FH, "/home/smenk/.filfolde/$file")..filfoldeshould be.filfolder, no?Path::Class::dir, you don't needopendir/readdir.$fhn, so it's creating files with no contents.$fhis opening a directory as though it was a file, which can't do anything useful. The only reason it doesn't cause problems is because you never use that one either.