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.

8 Comments

The above code is very hard to read. Is there no way to format it properly?

If you look at Ovid's post :

http://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?

opendir (DIR, $dir) or die "failed to open:$!";
...
closedir(dir);

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.

Leave a comment

About yuvaraj

user-pic I am new to perl. I am about to gather more knowledge and share my knowledge here.