Directory size calculator
#!c:\perl
print "Enter a directory \n";
chop ($dir=STDIN);
$i=0;
$store[$i]=$dir;
$i++;
readfiles();
sub readfiles
{
foreach $dir (@store)
{
opendir (DIR, $dir) or die "failed to open:$!";
@thefiles= readdir(DIR);
closedir(dir);
foreach $f (@thefiles)
{
unless ( ($f eq ".") || ($f eq "..") )
{
#print "$f \n";
$path=join("",$dir,"/",$f);
#print "$path \n";
if ( -d $path)
{
#print "$f a directory \n";
$store[$i]=$path;
$i++;
}
else
{
@fsdata=stat($path);
$a+= $fsdata[7];
}
}
}
}
print "$a \n";
}
foreach $store (@store)
{
print "$store \n";
}
The above script will help in calculating the size of the directory.
The above code is very hard to read. Is there no way to format it properly?
If you look at Ovid's post :
https://blogs.perl.org/users/ovid/2011/08/timemost-and-timeit.html
He's using a "code" tag, and class "prettyprint" (do a "view source") to wrap the code. Is this something you can look into?
Also, it is best practice to :
use strict
and use lexical vars e.g. "my".
Cheers,
Alastair
Hi Folks
See also:
#!/usr/bin/env perl
use File::Find;
# -------------
@ARGV = ('.') unless @ARGV;
my $sum = 0;
find sub { $sum += -s }, @ARGV;
1 while $sum =~ s/(\d)(\d\d\d)(?!\d)/$1,$2/;
print "@ARGV contains $sum bytes\n";
Do you really think this works like you think it does?
Thanks for your information Sherr. This is the first time i am posting a blog and that's why there is discrepancy in it's proper format. I will make a note of it and with my next post i'll surely follow a much professional format.
Hi confuseAcat,
I use to get the Disk space used for a particular directory using this script and it works as i expected. Do you find any problem with this.
are you able to install CPAN modules? (if not, then that's a big drawback to learning Perl)
searching for 'dir size' finds https://metacpan.org/module/Win32::DirSize
which sounds like it might already do this for you...?
Well, you are not closing the directory handle that you opened. It works, yes. Because in this case the call to closedir is superfluous. To be totally explicit: you are opening DIR, but you are closing dir.
Well that's right confuseAcat. I will correct it.