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:
The arguments passed to die() will be printed to STDERR for you, so you needn't bother with print().1 at script.pl line 10. Can't create logfile; Access is denied.
Update: Links fixed.
In reply to Re: Perl Script to count files and directories is not working.
by kejohm
in thread Perl Script to count files and directories is not working.
by manu_06
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |