First of all, use strictures (use strict; use warnings;)! This could show you some of the errors.
You first initialize a scalar $dir with a path but then overwrite it with for $dir ( @dirs ) { extracting from an undefined array @dirs.
you open and close OUTF, but then you print to stdout, so your output go to the shell and not to the log file.
Update: I didn't notice you are a new user; welcome to the Monastery!
Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."
| [reply] [d/l] |
A short program is just a long program that isn't finished yet. Always use use warnings;. Always use use strict;.
Do that now, and see what progress you achieve.
Once you get past declaring $dir, $directory_count, $file_count and $outfile, you will discover that your for-loop is iterating over and undefined array, @dirs. Since @dirs is empty, you never enter the loop, so no print statements.
No, we can't re-write it for you, do your own homework.
As Occam said: Entia non sunt multiplicanda praeter necessitatem.
| [reply] [d/l] [select] |
Hi,
Thanks for the reply. I declared strict and warnings and came to know my errors. In process of correcting them.
| [reply] |
The read_dir function from File::Slurp is also handy for getting a listing of directory entries. It filters out the special 'dot' directories by default.
Also, perltidy is handy for indenting your code.
use strict;
use warnings;
use File::Slurp;
my @dirs = ('./');
my $directory_count = 0;
my $file_count = 0;
my $outfile = 'log.txt';
open my $fh, '>', $outfile or die "can't create logfile; $!";
for my $dir (@dirs) {
for my $file (read_dir($dir)) {
if ( -f "$dir/$file" ) {
$directory_count++;
}
else {
$file_count++;
}
}
print $fh "Directories: $directory_count\n";
print $fh "Files: $file_count\n";
}
close $fh;
| [reply] [d/l] [select] |
Hi,
Thank a lot. Learned new things as i am new to perl.
| [reply] |
You could also look at the File::Find module for traversing directories. Here is your code rewritten using File::Find:
#!perl
use strict;
use warnings;
use File::Find;
my $dir = 'c:/My Projects/Perl Scripts/New Folder';
my $directory_count = 0;
my $file_count = 0;
my $outfile = 'log.txt';
find(
sub {
# $_ contains the name of the current file
# $File::Find::name contains the full path of the current file
+ relative
# to the directory given to the find() function
# $File::Find::dir contains the name of the current directory
if(-d $_){ # if file is a directory
$directory_count++;
}
elsif(-f $_) { # else if file is a plain file
$file_count++;
}
},
$dir
);
open my $log, q(>), $outfile or die "Can't create logfile; $!";
print {$log} "Directories: $directory_count\n";
print {$log} "Files: $file_count\n";
close $log;
Here are a few things regarding the code that you submitted:
Update: Links fixed. | [reply] [d/l] [select] |
Hi,
Thank you for the reply. Checked on my errors and its working.
| [reply] |
| [reply] |